Debian Codegraph @

mesonbuild/backend/ninjabackend.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2017 The Meson development team
3 # Copyright © 2023-2025 Intel Corporation
4
5 from __future__ import annotations
6
7 from collections import defaultdict, OrderedDict
8 from dataclasses import dataclass
9 from enum import Enum, unique
10 from functools import lru_cache
11 from pathlib import PurePath, Path
12 from textwrap import dedent
13 import dataclasses
14 import itertools
15 import json
16 import os
17 import pickle
18 import re
19 import subprocess
20 import typing as T
21
22 from . import backends
23 from .. import modules
24 from .. import mesonlib
25 from .. import build
26 from .. import mlog
27 from .. import compilers
28 from .. import tooldetect
29 from ..arglist import CompilerArgs
30 from ..compilers import Compiler, is_library
31 from ..linkers import ArLikeLinker, RSPFileSyntax, StaticLinker
32 from ..mesonlib import (
33 File, LibType, MachineChoice, MesonBugException, MesonException, OrderedSet, PerMachine,
34 ProgressBar, quote_arg, unique_list
35 )
36 from ..mesonlib import get_compiler_for_source, has_path_sep, is_parent_path, lookbehind, path_has_root
37 from ..options import OptionKey
38 from .backends import CleanTrees
39 from ..build import GeneratedList, InvalidArguments
40
41 if T.TYPE_CHECKING:
42 from typing_extensions import Literal, TypedDict
43
44 from .._typing import ImmutableListProtocol
45 from ..compilers.compilers import Language
46 from ..compilers.cs import CsCompiler
47 from ..compilers.fortran import FortranCompiler
48 from ..compilers.rust import RustCompiler
49 from ..compilers.swift import SwiftCompiler
50 from ..mesonlib import FileOrString
51 from .backends import TargetIntrospectionData, CompilerIntrospectionData, LinkerIntrospectionData
52
53 CommandArgTypes = T.TypeVar('CommandArgTypes', 'NinjaCommandArg', str, 'NinjaCommandArg | str')
54 CommandArgs = T.List[CommandArgTypes]
55 FileList = T.List[File] | T.List[str] | T.List[File | str]
56 ListifiedStr = str | T.List[str]
57 RUST_EDITIONS = Literal['2015', '2018', '2021', '2024']
58
59 class NinjaRuleArgs(TypedDict, total=False):
60 rspable: bool
61 rspfile_quote_style: RSPFileSyntax
62
63
64 FORTRAN_INCLUDE_PAT = r"^\s*#?include\s*['\"](\w+\.\w+)['\"]"
65 FORTRAN_MODULE_PAT = r"^\s*\bmodule\b\s+(\w+)\s*(?:!+.*)*$"
66 FORTRAN_SUBMOD_PAT = r"^\s*\bsubmodule\b\s*\((\w+:?\w+)\)\s*(\w+)"
67 FORTRAN_USE_PAT = r"^\s*use,?\s*(?:non_intrinsic)?\s*(?:::)?\s*(\w+)"
68
69 def cmd_quote(arg: str) -> str:
70 # see: https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/nf-shellapi-commandlinetoargvw#remarks
71
72 # backslash escape any existing double quotes
73 # any existing backslashes preceding a quote are doubled
74 arg = re.sub(r'(\\*)"', lambda m: '\\' * (len(m.group(1)) * 2 + 1) + '"', arg)
75 # any terminal backslashes likewise need doubling
76 arg = re.sub(r'(\\*)$', lambda m: '\\' * (len(m.group(1)) * 2), arg)
77 # and double quote
78 arg = f'"{arg}"'
79
80 return arg
81
82 # How ninja executes command lines differs between Unix and Windows
83 # (see https://ninja-build.org/manual.html#ref_rule_command)
84 if mesonlib.is_windows():
85 quote_func = cmd_quote
86 execute_wrapper = ['cmd', '/c'] # unused
87 rmfile_prefix = ['del', '/f', '/s', '/q', '{}', '&&']
88 else:
89 quote_func = quote_arg
90 execute_wrapper = []
91 rmfile_prefix = ['rm', '-f', '{}', '&&']
92
93 def gcc_rsp_quote(s: str) -> str:
94 # see: the function buildargv() in libiberty
95 #
96 # this differs from sh-quoting in that a backslash *always* escapes the
97 # following character, even inside single quotes.
98
99 s = s.replace('\\', '\\\\')
100
101 return quote_func(s)
102
103 # a conservative estimate of the command-line length limit
104 rsp_threshold = mesonlib.get_rsp_threshold()
105
106 # ninja variables whose value should remain unquoted. The value of these ninja
107 # variables (or variables we use them in) is interpreted directly by ninja
108 # (e.g. the value of the depfile variable is a pathname that ninja will read
109 # from, etc.), so it must not be shell quoted.
110 raw_names = {'DEPFILE_UNQUOTED', 'DESC', 'pool', 'description', 'targetdep', 'dyndep'}
111
112 NINJA_QUOTE_BUILD_PAT = re.compile(r"[$ :\n]")
113 NINJA_QUOTE_VAR_PAT = re.compile(r"[$ \n]")
114
115 def ninja_quote(text: str, is_build_line: bool = False) -> str:
116 if '\n' in text:
117 errmsg = f'''Ninja does not support newlines in rules. The content was:
118
119 {text}
120
121 Please report this error with a test case to the Meson bug tracker.'''
122 raise MesonException(errmsg)
123
124 quote_re = NINJA_QUOTE_BUILD_PAT if is_build_line else NINJA_QUOTE_VAR_PAT
125 if ' ' in text or '$' in text or (is_build_line and ':' in text):
126 return quote_re.sub(r'$\g<0>', text)
127
128 return text
129
130
131 @dataclass
132 class TargetDependencyScannerInfo:
133
134 """Information passed to the depscanner about a target.
135
136 :param private_dir: The private scratch directory for the target.
137 :param source2object: A mapping of source file names to the objects that
138 will be created from them.
139 :param sources: a list of sources mapping them to the language rules to use
140 to scan them.
141 """
142
143 private_dir: str
144 source2object: T.Dict[str, str]
145 sources: T.List[T.Tuple[str, Literal['cpp', 'fortran']]]
146
147
148 @unique
149 class Quoting(Enum):
150 both = 0
151 notShell = 1
152 notNinja = 2
153 none = 3
154
155 class NinjaCommandArg:
156 def __init__(self, s: str, quoting: Quoting = Quoting.both) -> None:
157 self.s = s
158 self.quoting = quoting
159
160 def __str__(self) -> str:
161 return self.s
162
163 @staticmethod
164 def list(l: T.List[str], q: Quoting) -> T.List[NinjaCommandArg]:
165 return [NinjaCommandArg(i, q) for i in l]
166
167 @dataclass
168 class NinjaComment:
169 comment: str
170
171 def write(self, outfile: T.TextIO) -> None:
172 for l in self.comment.split('\n'):
173 outfile.write('# ')
174 outfile.write(l)
175 outfile.write('\n')
176 outfile.write('\n')
177
178 class NinjaRule:
179 def __init__(self, rule: str, command: CommandArgs, args: CommandArgs,
180 description: str, rspable: bool = False, deps: T.Optional[str] = None,
181 depfile: T.Optional[str] = None, extra: T.Optional[str] = None,
182 rspfile_quote_style: RSPFileSyntax = RSPFileSyntax.GCC,
183 restat: bool = False):
184
185 def strToCommandArg(c: T.Union[NinjaCommandArg, str]) -> NinjaCommandArg:
186 if isinstance(c, NinjaCommandArg):
187 return c
188
189 # deal with common cases here, so we don't have to explicitly
190 # annotate the required quoting everywhere
191 if c == '&&':
192 # shell constructs shouldn't be shell quoted
193 return NinjaCommandArg(c, Quoting.notShell)
194 if c.startswith('$'):
195 varp = mesonlib.unwrap(re.match(r'\$\{?(\w*)\}?', c))
196 var: str = varp.group(1)
197 if var not in raw_names:
198 # ninja variables shouldn't be ninja quoted, and their value
199 # is already shell quoted
200 return NinjaCommandArg(c, Quoting.none)
201 else:
202 # shell quote the use of ninja variables whose value must
203 # not be shell quoted (as it also used by ninja)
204 return NinjaCommandArg(c, Quoting.notNinja)
205
206 return NinjaCommandArg(c)
207
208 self.name = rule
209 self.command: T.List[NinjaCommandArg] = [strToCommandArg(c) for c in command] # includes args which never go into a rspfile
210 self.args: T.List[NinjaCommandArg] = [strToCommandArg(a) for a in args] # args which will go into a rspfile, if used
211 self.description = description
212 self.deps = deps # depstyle 'gcc' or 'msvc'
213 self.depfile = depfile
214 self.extra = extra
215 self.restat = restat
216 self.rspable = rspable # if a rspfile can be used
217 self.refcount = 0
218 self.rsprefcount = 0
219 self.rspfile_quote_style = rspfile_quote_style
220 self.command_str = ' '.join([self._quoter(x) for x in self.command + self.args])
221 self.var_refs = [m for m in re.finditer(r'(\${\w+}|\$\w+)?[^$]*', self.command_str)
222 if m.start(1) != -1]
223
224 if self.depfile == '$DEPFILE':
225 self.depfile += '_UNQUOTED'
226
227 @staticmethod
228 def _quoter(x: NinjaCommandArg, qf: T.Callable[[str], str] = quote_func) -> str:
229 if x.quoting == Quoting.none:
230 return x.s
231 elif x.quoting == Quoting.notNinja:
232 return qf(x.s)
233 elif x.quoting == Quoting.notShell:
234 return ninja_quote(x.s)
235 return ninja_quote(qf(str(x)))
236
237 def write(self, outfile: T.TextIO) -> None:
238 rspfile_args = self.args
239 rspfile_quote_func: T.Callable[[str], str]
240 if self.rspfile_quote_style in {RSPFileSyntax.MSVC, RSPFileSyntax.TASKING}:
241 rspfile_quote_func = cmd_quote
242 rspfile_args = [NinjaCommandArg('$in_newline', arg.quoting) if arg.s == '$in' else arg for arg in rspfile_args]
243 else:
244 rspfile_quote_func = gcc_rsp_quote
245
246 def rule_iter() -> T.Iterable[str]:
247 if self.refcount:
248 yield ''
249 if self.rsprefcount:
250 yield '_RSP'
251
252 for rsp in rule_iter():
253 outfile.write(f'rule {self.name}{rsp}\n')
254 if rsp == '_RSP':
255 if self.rspfile_quote_style is RSPFileSyntax.TASKING:
256 outfile.write(' command = {} --option-file=$out.rsp\n'.format(' '.join([self._quoter(x) for x in self.command])))
257 else:
258 outfile.write(' command = {} @$out.rsp\n'.format(' '.join([self._quoter(x) for x in self.command])))
259 outfile.write(' rspfile = $out.rsp\n')
260 outfile.write(' rspfile_content = {}\n'.format(' '.join([self._quoter(x, rspfile_quote_func) for x in rspfile_args])))
261 else:
262 outfile.write(' command = {}\n'.format(self.command_str))
263 if self.deps:
264 outfile.write(f' deps = {self.deps}\n')
265 if self.depfile:
266 outfile.write(f' depfile = {self.depfile}\n')
267 outfile.write(f' description = {self.description}\n')
268 if self.restat:
269 outfile.write(' restat = 1\n')
270 if self.extra:
271 for l in self.extra.split('\n'):
272 outfile.write(' ')
273 outfile.write(l)
274 outfile.write('\n')
275 outfile.write('\n')
276
277 def _length_estimate(self, infiles: str, outfiles: str,
278 elems: T.List[T.Tuple[str, T.List[str]]]) -> int:
279 # determine variables
280 # this order of actions only approximates ninja's scoping rules, as
281 # documented at: https://ninja-build.org/manual.html#ref_scope
282 ninja_vars = dict(elems)
283 if self.deps is not None:
284 ninja_vars['deps'] = [self.deps]
285 if self.depfile is not None:
286 ninja_vars['depfile'] = [self.depfile]
287 ninja_vars['in'] = [infiles]
288 ninja_vars['out'] = [outfiles]
289
290 # expand variables in command
291 estimate = len(self.command_str)
292 for m in self.var_refs:
293 estimate -= m.end(1) - m.start(1)
294 chunk = m.group(1)
295 if chunk[1] == '{':
296 chunk = chunk[2:-1]
297 else:
298 chunk = chunk[1:]
299 chunk = ninja_vars.get(chunk, []) # undefined ninja variables are empty
300 estimate += len(' '.join(chunk))
301
302 # determine command length
303 return estimate
304
305 def should_use_rspfile(self, element: NinjaBuildElement) -> bool:
306 if not self.rspable:
307 return False
308
309 infilenames = ' '.join([ninja_quote(i, True) for i in element.infilenames])
310 outfilenames = ' '.join([ninja_quote(i, True) for i in element.outfilenames])
311
312 return self._length_estimate(infilenames,
313 outfilenames,
314 element.elems) >= rsp_threshold
315
316 class NinjaBuildElement:
317
318 rule: NinjaRule
319
320 def __init__(self, all_outputs: T.Set[str], outfilenames: ListifiedStr, rulename: str, infilenames: ListifiedStr, implicit_outs: T.Optional[T.List[str]] = None):
321 self.implicit_outfilenames = implicit_outs or []
322 if isinstance(outfilenames, str):
323 self.outfilenames = [outfilenames]
324 else:
325 self.outfilenames = outfilenames
326 assert isinstance(rulename, str)
327 self.rulename = rulename
328 if isinstance(infilenames, str):
329 self.infilenames = [infilenames]
330 else:
331 self.infilenames = infilenames
332 self.deps: T.Set[str] = set()
333 self.orderdeps: T.Set[str] = set()
334 self.elems: T.List[T.Tuple[str, T.List[str]]] = []
335 self.all_outputs = all_outputs
336 self.output_errors = ''
337
338 def add_dep(self, dep: ListifiedStr) -> None:
339 if isinstance(dep, list):
340 self.deps.update(dep)
341 else:
342 self.deps.add(dep)
343
344 def add_orderdep(self, dep: ListifiedStr) -> None:
345 if isinstance(dep, list):
346 self.orderdeps.update(dep)
347 else:
348 self.orderdeps.add(dep)
349
350 def add_item(self, name: str, elems: T.Union[ListifiedStr, CompilerArgs]) -> None:
351 # Always convert from GCC-style argument naming to the naming used by the
352 # current compiler. Also filter system include paths, deduplicate, etc.
353 if isinstance(elems, CompilerArgs):
354 elems = elems.to_native()
355 if isinstance(elems, str):
356 elems = [elems]
357 self.elems.append((name, elems))
358
359 if name == 'DEPFILE':
360 self.elems.append((name + '_UNQUOTED', elems))
361
362 @mesonlib.lazy_property
363 def _should_use_rspfile(self) -> bool:
364 # 'phony' is a rule built-in to ninja
365 if self.rulename == 'phony':
366 return False
367
368 if not self.rule:
369 raise MesonBugException(f"build statement for {self.outfilenames} references unmapped rule {self.rulename}")
370
371 return self.rule.should_use_rspfile(self)
372
373 def count_rule_references(self) -> None:
374 if self.rulename != 'phony':
375 if self._should_use_rspfile:
376 self.rule.rsprefcount += 1
377 else:
378 self.rule.refcount += 1
379
380 def write(self, outfile: T.TextIO) -> None:
381 if self.output_errors:
382 raise MesonException(self.output_errors)
383 ins = ' '.join([ninja_quote(i, True) for i in self.infilenames])
384 outs = ' '.join([ninja_quote(i, True) for i in self.outfilenames])
385 implicit_outs = ' '.join([ninja_quote(i, True) for i in self.implicit_outfilenames])
386 if implicit_outs:
387 implicit_outs = ' | ' + implicit_outs
388 use_rspfile = self._should_use_rspfile
389 if use_rspfile:
390 rulename = self.rulename + '_RSP'
391 mlog.debug(f'Command line for building {self.outfilenames} is long, using a response file')
392 else:
393 rulename = self.rulename
394 line = f'build {outs}{implicit_outs}: {rulename} {ins}'
395 if len(self.deps) > 0:
396 line += ' | ' + ' '.join([ninja_quote(x, True) for x in sorted(self.deps)])
397 if len(self.orderdeps) > 0:
398 orderdeps = [str(x) for x in self.orderdeps]
399 line += ' || ' + ' '.join([ninja_quote(x, True) for x in sorted(orderdeps)])
400 line += '\n'
401 # This is the only way I could find to make this work on all
402 # platforms including Windows command shell. Slash is a dir separator
403 # on Windows, too, so all characters are unambiguous and, more importantly,
404 # do not require quoting, unless explicitly specified, which is necessary for
405 # the csc compiler.
406 line = line.replace('\\', '/')
407 if mesonlib.is_windows():
408 # Support network paths as backslash, otherwise they are interpreted as
409 # arguments for compile/link commands when using MSVC
410 line = ' '.join(
411 (l.replace('//', '\\\\', 1) if l.startswith('//') else l)
412 for l in line.split(' ')
413 )
414 outfile.write(line)
415
416 if use_rspfile:
417 if self.rule.rspfile_quote_style in {RSPFileSyntax.MSVC, RSPFileSyntax.TASKING}:
418 qf = cmd_quote
419 else:
420 qf = gcc_rsp_quote
421 else:
422 qf = quote_func
423
424 for e in self.elems:
425 (name, elems) = e
426 should_quote = name not in raw_names
427 line = f' {name} = '
428 newelems = []
429 for i in elems:
430 if mesonlib.is_windows():
431 # Support network paths with double-backslash (UNC)
432 # Officially //foo/bar is not an UNC and mostly doesn't work
433 # in Windows
434 if i.startswith('//'):
435 i = i.replace('//', '\\\\', 1)
436 if not should_quote or i == '&&': # Hackety hack hack
437 newelems.append(ninja_quote(i))
438 else:
439 newelems.append(ninja_quote(qf(i)))
440 line += ' '.join(newelems)
441 line += '\n'
442 outfile.write(line)
443 outfile.write('\n')
444
445 def check_outputs(self) -> None:
446 for n in self.outfilenames:
447 if n in self.all_outputs:
448 self.output_errors = f'Multiple producers for Ninja target "{n}". Please rename your targets.'
449 self.all_outputs.add(n)
450
451 @dataclass
452 class NinjaBuild:
453 rules: list[NinjaRule | NinjaComment] = dataclasses.field(default_factory=list, init=False)
454 ruledict: dict[str, NinjaRule] = dataclasses.field(default_factory=dict, init=False)
455 build_elements: list[NinjaBuildElement | NinjaComment] = dataclasses.field(default_factory=list, init=False)
456
457 def add_rule_comment(self, comment: NinjaComment) -> None:
458 self.rules.append(comment)
459
460 def add_build_comment(self, comment: NinjaComment) -> None:
461 self.build_elements.append(comment)
462
463 def add_rule(self, rule: NinjaRule) -> None:
464 if rule.name in self.ruledict:
465 raise MesonException(f'Tried to add rule {rule.name} twice.')
466 self.rules.append(rule)
467 self.ruledict[rule.name] = rule
468
469 def has_rule(self, name: str) -> bool:
470 return name in self.ruledict
471
472 def should_use_rspfile(self, build: NinjaBuildElement) -> bool:
473 if build.rulename == 'phony':
474 return False
475
476 if build.rulename in self.ruledict:
477 return self.ruledict[build.rulename].should_use_rspfile(build)
478
479 mlog.warning(f"build statement for {build.outfilenames} references nonexistent rule {build.rulename}")
480 return False
481
482 def add_build(self, build: NinjaBuildElement) -> None:
483 build.check_outputs()
484 self.build_elements.append(build)
485
486 if build.rulename != 'phony':
487 # reference rule
488 if build.rulename in self.ruledict:
489 build.rule = self.ruledict[build.rulename]
490 else:
491 mlog.warning(f"build statement for {build.outfilenames} references nonexistent rule {build.rulename}")
492
493 def write(self, outfile: T.TextIO) -> None:
494 for b in self.build_elements:
495 if isinstance(b, NinjaBuildElement):
496 b.count_rule_references()
497
498 for r in self.rules:
499 r.write(outfile)
500
501 for b in ProgressBar(self.build_elements, desc='Writing build.ninja'):
502 b.write(outfile)
503
504 @dataclass
505 class RustDep:
506
507 name: str
508
509 # equal to the order value of the `RustCrate`
510 crate: int
511
512 def to_json(self) -> T.Dict[str, object]:
513 return {
514 "crate": self.crate,
515 "name": self.name,
516 }
517
518 @dataclass
519 class RustCrate:
520
521 # When the json file is written, the list of Crates will be sorted by this
522 # value
523 order: int
524
525 display_name: str
526 root_module: str
527 crate_type: str
528 target_name: str
529 edition: RUST_EDITIONS
530 deps: T.List[RustDep]
531 cfg: T.List[str]
532
533 # This is set to True for members of this project, and False for all
534 # subprojects
535 is_workspace_member: bool
536 proc_macro_dylib_path: T.Optional[str] = None
537
538 def to_json(self) -> T.Dict[str, object]:
539 ret: T.Dict[str, object] = {
540 "display_name": self.display_name,
541 "root_module": self.root_module,
542 "edition": self.edition,
543 "cfg": self.cfg,
544 "is_proc_macro": self.proc_macro_dylib_path is not None,
545 "deps": [d.to_json() for d in self.deps],
546 }
547
548 if (proc_macro := self.proc_macro_dylib_path) is not None:
549 ret["proc_macro_dylib_path"] = proc_macro
550
551 return ret
552
553
554 @dataclass
555 class ImportStdInfo:
556 gen_target: NinjaBuildElement
557 gen_module_file: str
558 gen_objects: T.List[str]
559
560 class NinjaBackend(backends.Backend):
561
562 def __init__(self, build: T.Optional[build.Build]):
563 super().__init__(build)
564 self.name = 'ninja'
565 self.ninja = NinjaBuild()
566 self.ninja_filename = 'build.ninja'
567 self.fortran_deps: T.Dict[str, T.Dict[str, File]] = {}
568 self.all_outputs: T.Set[str] = set()
569 self.all_pch: T.Dict[str, T.Set[str]] = defaultdict(set)
570 self.all_structured_sources: T.Set[str] = set()
571 # 1st level: target; 2nd: compiler or linker; 3rd: individual keys
572 self.introspection_data: dict[str, dict[tuple[str, tuple[str, ...]] | tuple[str, ...],
573 TargetIntrospectionData]] = {}
574 self.created_llvm_ir_rule = PerMachine(False, False)
575 self.rust_crates: T.Dict[str, RustCrate] = {}
576 self.implicit_meson_outs: T.List[str] = []
577 self._uses_dyndeps = False
578 self._generated_header_cache: T.Dict[str, T.List[FileOrString]] = {}
579 # nvcc chokes on thin archives:
580 # nvlink fatal : Could not open input file 'libfoo.a.p'
581 # nvlink fatal : elfLink internal error
582 # hence we disable them if 'cuda' is enabled globally. See also
583 # - https://github.com/mesonbuild/meson/pull/9453
584 # - https://github.com/mesonbuild/meson/issues/9479#issuecomment-953485040
585 self.allow_thin_archives = PerMachine[bool](True, True)
586 self.import_std: T.Optional[ImportStdInfo] = None
587
588 def create_phony_target(self, dummy_outfile: str, rulename: str, phony_infilenames: ListifiedStr) -> NinjaBuildElement:
589 '''
590 We need to use aliases for targets that might be used as directory
591 names to workaround a Ninja bug that breaks `ninja -t clean`.
592 This is used for 'reserved' targets such as 'test', 'install',
593 'benchmark', etc, and also for RunTargets.
594 https://github.com/mesonbuild/meson/issues/1644
595 '''
596 if dummy_outfile.startswith('meson-internal__'):
597 raise AssertionError(f'Invalid usage of create_phony_target with {dummy_outfile!r}')
598
599 to_name = f'meson-internal__{dummy_outfile}'
600 elem = NinjaBuildElement(self.all_outputs, dummy_outfile, 'phony', to_name)
601 self.add_build(elem)
602
603 return NinjaBuildElement(self.all_outputs, to_name, rulename, phony_infilenames)
604
605 def detect_vs_dep_prefix(self, tempfilename: str) -> T.TextIO:
606 '''VS writes its dependency in a locale dependent format.
607 Detect the search prefix to use.'''
608 # TODO don't hard-code host
609 for compiler in self.environment.coredata.compilers.host.values():
610 # Have to detect the dependency format
611
612 # IFort / masm on windows is MSVC like, but doesn't have /showincludes
613 if compiler.language in {'fortran', 'masm'}:
614 continue
615 if compiler.id == 'pgi' and mesonlib.is_windows():
616 # for the purpose of this function, PGI doesn't act enough like MSVC
617 return open(tempfilename, 'a', encoding='utf-8')
618 if compiler.get_argument_syntax() == 'msvc':
619 break
620 else:
621 # None of our compilers are MSVC, we're done.
622 return open(tempfilename, 'a', encoding='utf-8')
623 filebase = 'incdetect.' + compilers.lang_suffixes[compiler.language][0]
624 filename = os.path.join(self.environment.get_scratch_dir(),
625 filebase)
626 with open(filename, 'w', encoding='utf-8') as f:
627 f.write(dedent('''\
628 #include"incdetect2"
629 int dummy;
630 '''))
631 filename_inc = os.path.join(self.environment.get_scratch_dir(),
632 'incdetect2')
633 with open(filename_inc, 'w', encoding='utf-8') as f:
634 pass
635
636 # The output of cl dependency information is language
637 # and locale dependent. Any attempt at converting it to
638 # Python strings leads to failure. We _must_ do this detection
639 # in raw byte mode and write the result in raw bytes.
640 #
641 # Pass the compiler's external args (e.g. -I flags from c_args /
642 # cpp_args in a native file) so that cl.exe can locate system headers
643 # even when the INCLUDE environment variable is not set — for example,
644 # when using a bundled MSVC toolchain outside a VS Developer Shell.
645 extra_args = self.environment.coredata.get_external_args(
646 MachineChoice.HOST, compiler.language)
647 pc = subprocess.Popen(compiler.get_exelist() +
648 ['/showIncludes', '/c', filebase] + extra_args,
649 cwd=self.environment.get_scratch_dir(),
650 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
651 (stdout, stderr) = pc.communicate()
652
653 # 'Note: including file: d:\build\meson-private\incdetect2', however
654 # different locales have different messages with a different
655 # number of colons. Match up to the drive name 'd:\' or
656 # a relative path '.\'.
657 # When used in cross compilation, the path separator is a
658 # forward slash rather than a backslash so handle both; i.e.
659 # the path is /build/meson-private/incdetect or ./incdetect2.
660 # With certain cross compilation wrappings of MSVC, the paths
661 # use backslashes, but without the leading drive name, so
662 # allow the path to start with any path separator, i.e.
663 # \build\meson-private\incdetect2
664 matchre = re.compile(rb"^(.*\s)([a-zA-Z]:[\\/]|\.?[\\/]).*incdetect2$")
665
666 def detect_prefix(out: bytes) -> T.TextIO:
667 for line in re.split(rb'\r?\n', out):
668 match = matchre.match(line)
669 if match:
670 with open(tempfilename, 'ab') as binfile:
671 binfile.write(b'msvc_deps_prefix = ' + match.group(1) + b'\n')
672 return open(tempfilename, 'a', encoding='utf-8')
673 return None
674
675 # Some cl wrappers (e.g. Squish Coco) output dependency info
676 # to stderr rather than stdout
677 result = detect_prefix(stdout) or detect_prefix(stderr)
678 if result:
679 return result
680
681 raise MesonException(f'Could not determine vs dep dependency prefix string. output: {stderr!r} {stdout!r}')
682
683 def generate(self, capture: bool = False, vslite_ctx: T.Optional[T.Dict] = None) -> T.Optional[T.Dict[str, T.Dict[Language, T.List[str]]]]:
684 captured_compile_args_per_target: T.Dict[str, T.Dict[Language, T.List[str]]] = {}
685 if vslite_ctx:
686 # We don't yet have a use case where we'd expect to make use of this,
687 # so no harm in catching and reporting something unexpected.
688 raise MesonBugException('We do not expect the ninja backend to be given a valid \'vslite_ctx\'')
689 if self.environment:
690 for for_machine in MachineChoice:
691 if 'cuda' in self.environment.coredata.compilers[for_machine]:
692 mlog.debug('cuda enabled globally, disabling thin archives for {}, since nvcc/nvlink cannot handle thin archives natively'.format(for_machine))
693 self.allow_thin_archives[for_machine] = False
694
695 ninja = tooldetect.detect_ninja_command_and_version(log=True)
696 if self.environment.coredata.optstore.get_value_for(OptionKey('vsenv')):
697 builddir = Path(self.environment.get_build_dir())
698 try:
699 # For prettier printing, reduce to a relative path. If
700 # impossible (e.g., because builddir and cwd are on
701 # different Windows drives), skip and use the full path.
702 builddir = builddir.relative_to(Path.cwd())
703 except ValueError:
704 pass
705 meson_command = mesonlib.join_args(mesonlib.get_meson_command())
706 mlog.log()
707 mlog.log('Visual Studio environment is needed to run Ninja. It is recommended to use Meson wrapper:')
708 mlog.log(f'{meson_command} compile -C {builddir}')
709 if ninja is None:
710 raise MesonException('Could not detect Ninja v1.8.2 or newer')
711 (self.ninja_command, self.ninja_version) = ninja
712 self.ninja_has_dyndeps = mesonlib.version_compare(self.ninja_version, '>=1.10.0')
713 outfilename = os.path.join(self.environment.get_build_dir(), self.ninja_filename)
714 tempfilename = outfilename + '~'
715 with open(tempfilename, 'w', encoding='utf-8') as outfile:
716 outfile.write(f'# This is the build file for project "{self.build.get_project()}"\n')
717 outfile.write('# It is autogenerated by the Meson build system.\n')
718 outfile.write('# Do not edit by hand.\n\n')
719 outfile.write('ninja_required_version = 1.8.2\n\n')
720
721 num_pools = self.environment.coredata.optstore.get_value_for('backend_max_links')
722 assert isinstance(num_pools, int)
723 if num_pools > 0:
724 outfile.write(f'''pool link_pool
725 depth = {num_pools}
726
727 ''')
728
729 with self.detect_vs_dep_prefix(tempfilename) as outfile:
730 self.generate_rules()
731 self.generate_phony()
732 self.add_build_comment(NinjaComment('Build rules for targets'))
733
734 # Optionally capture compile args per target, for later use (i.e. VisStudio project's NMake intellisense include dirs, defines, and compile options).
735 if capture:
736 for target in self.build.get_targets().values():
737 if isinstance(target, build.BuildTarget):
738 captured_compile_args_per_target[target.get_id()] = self.generate_common_compile_args_per_src_type(target)
739
740 for t in ProgressBar(self.build.get_targets().values(), desc='Generating targets'):
741 self.generate_target(t)
742 mlog.log_timestamp("Targets generated")
743 self.add_build_comment(NinjaComment('Test rules'))
744 self.generate_tests()
745 mlog.log_timestamp("Tests generated")
746 self.add_build_comment(NinjaComment('Install rules'))
747 self.generate_install()
748 mlog.log_timestamp("Install generated")
749 self.generate_dist()
750 mlog.log_timestamp("Dist generated")
751 key = OptionKey('b_coverage')
752 if key in self.environment.coredata.optstore and\
753 self.environment.coredata.optstore.get_value_for('b_coverage'):
754 gcovr_exe, gcovr_version, lcov_exe, lcov_version, genhtml_exe, llvm_cov_exe = tooldetect.find_coverage_tools(self.environment.coredata)
755 mlog.debug(f'Using {gcovr_exe} ({gcovr_version}), {lcov_exe} and {llvm_cov_exe} for code coverage')
756 if gcovr_exe or (lcov_exe and genhtml_exe):
757 self.add_build_comment(NinjaComment('Coverage rules'))
758 self.generate_coverage_rules(gcovr_exe, gcovr_version, llvm_cov_exe)
759 mlog.log_timestamp("Coverage rules generated")
760 else:
761 # FIXME: since we explicitly opted in, should this be an error?
762 # The docs just say these targets will be created "if possible".
763 mlog.warning('Need gcovr or lcov/genhtml to generate any coverage reports')
764 self.add_build_comment(NinjaComment('Suffix'))
765 self.generate_utils()
766 mlog.log_timestamp("Utils generated")
767 self.generate_ending()
768
769 self.ninja.write(outfile)
770 mlog.log_timestamp("build.ninja generated")
771
772 default = 'default all\n\n'
773 outfile.write(default)
774 # Only overwrite the old build file after the new one has been
775 # fully created.
776 os.replace(tempfilename, outfilename)
777 mlog.cmd_ci_include(outfilename) # For CI debugging
778 # Refresh Ninja's caches. https://github.com/ninja-build/ninja/pull/1685
779 # Cannot use when running with dyndeps: https://github.com/ninja-build/ninja/issues/1952
780 if ((mesonlib.version_compare(self.ninja_version, '>= 1.12.0') or
781 (mesonlib.version_compare(self.ninja_version, '>=1.10.0') and not self._uses_dyndeps))
782 and os.path.exists(os.path.join(self.environment.build_dir, '.ninja_log'))):
783 subprocess.call(self.ninja_command + ['-t', 'restat'], cwd=self.environment.build_dir)
784 subprocess.call(self.ninja_command + ['-t', 'cleandead'], cwd=self.environment.build_dir)
785 self.generate_compdb()
786 self.generate_rust_project_json()
787
788 return captured_compile_args_per_target
789
790 def generate_rust_project_json(self) -> None:
791 """Generate a rust-analyzer compatible rust-project.json file."""
792 if not self.rust_crates:
793 return
794 with open(os.path.join(self.environment.get_build_dir(), 'rust-project.json'),
795 'w', encoding='utf-8') as f:
796 compiler = T.cast('RustCompiler', self.environment.coredata.compilers.host['rust'])
797 sysroot = compiler.get_sysroot()
798 json.dump(
799 {
800 "sysroot": sysroot,
801 "sysroot_src": os.path.join(sysroot, 'lib/rustlib/src/rust/library/'),
802 "crates": [c.to_json() for c in self.rust_crates.values()],
803 },
804 f, indent=4)
805
806 # http://clang.llvm.org/docs/JSONCompilationDatabase.html
807 def generate_compdb(self) -> None:
808 rules = []
809 # TODO: Rather than an explicit list here, rules could be marked in the
810 # rule store as being wanted in compdb
811 for for_machine in MachineChoice:
812 for compiler in self.environment.coredata.compilers[for_machine].values():
813 rules += [f"{rule}{ext}" for rule in [self.compiler_to_rule_name(compiler)]
814 for ext in ['', '_RSP']]
815 rules += [f"{rule}{ext}" for rule in [self.compiler_to_pch_rule_name(compiler)]
816 for ext in ['', '_RSP']]
817 # Add custom MIL link rules to get the files compiled by the TASKING compiler family to MIL files included in the database
818 if compiler.get_id() == 'tasking':
819 rule = self.get_compiler_rule_name('tasking_mil_compile', compiler.for_machine)
820 rules.append(rule)
821 rules.append(f'{rule}_RSP')
822 compdb_options = ['-x'] if mesonlib.version_compare(self.ninja_version, '>=1.9') else []
823 ninja_compdb = self.ninja_command + ['-t', 'compdb'] + compdb_options + rules
824 builddir = self.environment.get_build_dir()
825 try:
826 jsondb = subprocess.check_output(ninja_compdb, cwd=builddir)
827 with open(os.path.join(builddir, 'compile_commands.json'), 'wb') as f:
828 f.write(jsondb)
829 except Exception:
830 mlog.warning('Could not create compilation database.', fatal=False)
831
832 # Get all generated headers. Any source file might need them so
833 # we need to add an order dependency to them.
834 def get_generated_headers(self, target: build.BuildTarget) -> T.List[FileOrString]:
835 tid = target.get_id()
836 if tid in self._generated_header_cache:
837 return self._generated_header_cache[tid]
838 header_deps: T.List[FileOrString] = []
839 # XXX: Why don't we add deps to CustomTarget headers here?
840 for genlist in target.get_generated_sources():
841 if isinstance(genlist, (build.CustomTarget, build.CustomTargetIndex)):
842 continue
843 for src in genlist.get_outputs():
844 if compilers.is_header(src):
845 header_deps.append(self.get_target_generated_dir(target, genlist, src))
846 if target.vala_header:
847 vala_header = File.from_built_file(self.get_target_dir(target), target.vala_header)
848 header_deps.append(vala_header)
849 # Recurse and find generated headers
850 for dep in itertools.chain(target.link_targets, target.link_whole_targets):
851 if isinstance(dep, (build.StaticLibrary, build.SharedLibrary)):
852 header_deps += self.get_generated_headers(dep)
853 if isinstance(target, build.CompileTarget):
854 header_deps.extend(target.get_generated_headers())
855 self._generated_header_cache[tid] = header_deps
856 return header_deps
857
858 def get_target_generated_sources(self, target: build.BuildTarget) -> T.MutableMapping[str, build.TargetSources]:
859 """
860 Returns a dictionary with the keys being the path to the file
861 (relative to the build directory) and the value being the File object
862 representing the same path.
863 """
864 srcs: T.MutableMapping[str, build.TargetSources] = {}
865 for gensrc in target.get_generated_sources():
866 for s in gensrc.get_outputs():
867 rel_src = self.get_target_generated_dir(target, gensrc, s)
868 srcs[rel_src] = File.from_built_relative(rel_src)
869 return srcs
870
871 def get_target_sources(self, target: build.BuildTarget) -> T.MutableMapping[str, File]:
872 srcs: T.MutableMapping[str, File] = OrderedDict()
873 for s in target.get_sources():
874 # BuildTarget sources are always mesonlib.File files which are
875 # either in the source root, or generated with configure_file and
876 # in the build root
877 if not isinstance(s, File):
878 raise InvalidArguments(f'All sources in target {s!r} must be of type mesonlib.File')
879 f = s.rel_to_builddir(self.build_to_src)
880 srcs[f] = s
881 return srcs
882
883 def get_target_source_can_unity(self, target: build.BuildTarget, source: FileOrString) -> bool:
884 if isinstance(source, File):
885 source = source.fname
886 if compilers.is_llvm_ir(source) or \
887 compilers.is_assembly(source):
888 return False
889 suffix = os.path.splitext(source)[1][1:].lower()
890 for lang in backends.LANGS_CANT_UNITY:
891 if lang not in target.compilers:
892 continue
893 if suffix in target.compilers[lang].file_suffixes:
894 return False
895 return True
896
897 def create_target_source_introspection(self, target: build.Target, comp: compilers.Compiler,
898 parameters: CompilerArgs | T.List[str],
899 sources: FileList,
900 generated_sources: FileList,
901 unity_sources: list[File] | None = None) -> None:
902 '''
903 Adds the source file introspection information for a language of a target
904
905 Internal introspection storage format:
906 self.introspection_data = {
907 '<target ID>': {
908 <id tuple>: {
909 'language: 'lang',
910 'compiler': ['comp', 'exe', 'list'],
911 'parameters': ['UNIQUE', 'parameter', 'list'],
912 'sources': [],
913 'generated_sources': [],
914 }
915 }
916 }
917 '''
918 tid = target.get_id()
919 lang = comp.get_language()
920 tgt = self.introspection_data[tid]
921 # Find an existing entry or create a new one
922 id_hash: tuple[str, tuple] = (lang, tuple(parameters))
923
924 src_block: T.Optional[CompilerIntrospectionData]
925 src_block = T.cast('T.Optional[CompilerIntrospectionData]', tgt.get(id_hash, None))
926 if src_block is None:
927 # Convert parameters
928 if isinstance(parameters, CompilerArgs):
929 parameters = parameters.to_native(copy=True)
930 parameters = comp.compute_parameters_with_absolute_paths(parameters, self.build_dir)
931 # The new entry
932 src_block = {
933 'language': lang,
934 'machine': comp.for_machine.get_lower_case_name(),
935 'compiler': comp.get_exelist(),
936 'parameters': parameters,
937 'sources': [],
938 'generated_sources': [],
939 'unity_sources': [],
940 }
941 tgt[id_hash] = src_block
942
943 def compute_path(file: FileOrString) -> str:
944 """ Make source files absolute """
945 if isinstance(file, File):
946 return file.absolute_path(self.source_dir, self.build_dir)
947 return os.path.normpath(os.path.join(self.build_dir, file))
948
949 src_block['sources'].extend(compute_path(x) for x in sources)
950 src_block['generated_sources'].extend(compute_path(x) for x in generated_sources)
951 if unity_sources:
952 src_block['unity_sources'].extend(compute_path(x) for x in unity_sources)
953
954 def create_target_linker_introspection(self, target: build.Target, linker: T.Union[Compiler, StaticLinker], parameters: CompilerArgs) -> None:
955 tid = target.get_id()
956 tgt = self.introspection_data[tid]
957 lnk_hash: tuple[str, ...] = tuple(parameters)
958 lnk_block: T.Optional[LinkerIntrospectionData]
959 lnk_block = T.cast('T.Optional[LinkerIntrospectionData]', tgt.get(lnk_hash, None))
960 if lnk_block is None:
961 paramlist = parameters.to_native(copy=True)
962
963 if isinstance(linker, Compiler):
964 linkers = linker.get_linker_exelist()
965 else:
966 linkers = linker.get_exelist()
967
968 lnk_block = {
969 'linker': linkers,
970 'parameters': paramlist,
971 }
972 tgt[lnk_hash] = lnk_block
973
974 def generate_target(self, target: T.Union[build.Target]) -> None:
975 if isinstance(target, build.CustomTarget):
976 self.generate_custom_target(target)
977 return
978 if isinstance(target, build.RunTarget):
979 self.generate_run_target(target)
980 return
981 assert isinstance(target, build.BuildTarget)
982 os.makedirs(self.get_target_private_dir_abs(target), exist_ok=True)
983 compiled_sources: T.List[str] = []
984 source2object: T.Dict[str, str] = {}
985 name = target.get_id()
986 if name in self.processed_targets:
987 return
988 self.processed_targets.add(name)
989 # Initialize an empty introspection source list
990 self.introspection_data[name] = {}
991 # Generate rules for all dependency targets
992 self.process_target_dependencies(target)
993
994 self.generate_shlib_aliases(target, self.get_target_dir(target))
995
996 # Generate rules for GeneratedLists
997 self.generate_generator_list_rules(target)
998
999 # If target uses a language that cannot link to C objects,
1000 # just generate for that language and return.
1001 if isinstance(target, build.Jar):
1002 self.generate_jar_target(target)
1003 return
1004 if 'cs' in target.compilers:
1005 self.generate_cs_target(target)
1006 return
1007 if 'swift' in target.compilers:
1008 self.generate_swift_target(target)
1009 return
1010
1011 # CompileTarget compiles all its sources and does not do a final link.
1012 # This is, for example, a preprocessor.
1013 is_compile_target = isinstance(target, build.CompileTarget)
1014
1015 # Preexisting target C/C++ sources to be built; dict of full path to
1016 # source relative to build root and the original File object.
1017 target_sources: T.MutableMapping[str, File]
1018
1019 # GeneratedList and CustomTarget sources to be built; dict of the full
1020 # path to source relative to build root and the generating target/list
1021 generated_sources: T.MutableMapping[str, build.TargetSources]
1022
1023 # List of sources that have been transpiled from a DSL (like Vala) into
1024 # a language that is handled below, such as C or C++
1025 transpiled_sources: T.List[str]
1026
1027 if target.uses_vala():
1028 # Sources consumed by valac are filtered out. These only contain
1029 # C/C++ sources, objects, generated libs, and unknown sources now.
1030 target_sources, generated_sources, \
1031 transpiled_sources = self.generate_vala_compile(target)
1032 elif 'cython' in target.compilers:
1033 target_sources, generated_sources, \
1034 transpiled_sources = self.generate_cython_transpile(target)
1035 else:
1036 target_sources = self.get_target_sources(target)
1037 generated_sources = self.get_target_generated_sources(target)
1038 transpiled_sources = []
1039 self.scan_fortran_module_outputs(target)
1040
1041 # Generate rules for building the remaining source files in this target
1042 outname = self.get_target_filename(target)
1043 obj_list = []
1044 is_unity = self.is_unity(target)
1045 header_deps = []
1046 unity_src: list[File] = []
1047 unity_deps = [] # Generated sources that must be built before compiling a Unity target.
1048 header_deps += self.get_generated_headers(target)
1049
1050 if is_unity:
1051 # Warn about incompatible sources if a unity build is enabled
1052 langs = set(target.compilers.keys())
1053 langs_cant = langs.intersection(backends.LANGS_CANT_UNITY)
1054 if langs_cant:
1055 langs_are = langs = ', '.join(langs_cant).upper()
1056 langs_are += ' are' if len(langs_cant) > 1 else ' is'
1057 msg = f'{langs_are} not supported in Unity builds yet, so {langs} ' \
1058 f'sources in the {target.name!r} target will be compiled normally'
1059 mlog.log(mlog.red('FIXME'), msg)
1060
1061 # Get a list of all generated headers that will be needed while building
1062 # this target's sources (generated sources and preexisting sources).
1063 # This will be set as dependencies of all the target's sources. At the
1064 # same time, also deal with generated sources that need to be compiled.
1065 generated_source_files: T.List[File] = []
1066 for rel_src in generated_sources:
1067 raw_src = File.from_built_relative(rel_src)
1068 if compilers.is_source(rel_src):
1069 if is_unity and self.get_target_source_can_unity(target, rel_src):
1070 unity_deps.append(raw_src)
1071 unity_src.append(raw_src)
1072 else:
1073 generated_source_files.append(raw_src)
1074 elif compilers.is_object(rel_src):
1075 obj_list.append(rel_src)
1076 elif compilers.is_library(rel_src) or modules.is_module_library(rel_src):
1077 pass
1078 elif is_compile_target:
1079 generated_source_files.append(raw_src)
1080 else:
1081 # Assume anything not specifically a source file is a header. This is because
1082 # people generate files with weird suffixes (.inc, .fh) that they then include
1083 # in their source files.
1084 header_deps.append(raw_src)
1085
1086 # For D language, the object of generated source files are added
1087 # as order only deps because other files may depend on them
1088 d_generated_deps = []
1089
1090 # These are the generated source files that need to be built for use by
1091 # this target. We create the Ninja build file elements for this here
1092 # because we need `header_deps` to be fully generated in the above loop.
1093 for src in generated_source_files:
1094 if not compilers.is_separate_compile(src):
1095 continue
1096 if compilers.is_llvm_ir(src):
1097 o, s = self.generate_llvm_ir_compile(target, src)
1098 else:
1099 o, s = self.generate_single_compile(target, src, True, order_deps=header_deps)
1100 compiled_sources.append(s)
1101 source2object[s] = o
1102 obj_list.append(o)
1103 if s.split('.')[-1] in compilers.lang_suffixes['d']:
1104 d_generated_deps.append(o)
1105
1106 use_pch = self.target_uses_pch(target)
1107 if use_pch and target.has_pch():
1108 pch_objects = self.generate_pch(target, header_deps=header_deps)
1109 else:
1110 pch_objects = []
1111
1112 o, od = self.flatten_object_list(target)
1113 obj_list.extend(o)
1114 fortran_order_deps = self.get_fortran_order_deps(od)
1115
1116 fortran_inc_args: T.List[str] = []
1117 if target.uses_fortran():
1118 fortran_inc_args = mesonlib.listify([target.compilers['fortran'].get_include_args(
1119 self.get_target_private_dir(t), is_system=False) for t in od if t.uses_fortran()])
1120
1121 # add the private directories of all transitive dependencies, which
1122 # are needed for their mod files
1123 fc = target.compilers['fortran']
1124 for t in target.get_all_linked_targets():
1125 fortran_inc_args.extend(fc.get_include_args(
1126 self.get_target_private_dir(t), False))
1127
1128 # Generate compilation targets for sources generated by transpilers.
1129 #
1130 # Do not try to unity-build the generated source files, as these
1131 # often contain duplicate symbols and will fail to compile properly.
1132 #
1133 # Gather all generated source files and header before generating the
1134 # compilation rules, to be able to add correct dependencies on the
1135 # generated headers.
1136 transpiled_source_files = []
1137 for src in transpiled_sources:
1138 raw_src = File.from_built_relative(src)
1139 # Generated targets are ordered deps because the must exist
1140 # before the sources compiling them are used. After the first
1141 # compile we get precise dependency info from dep files.
1142 # This should work in all cases. If it does not, then just
1143 # move them from orderdeps to proper deps.
1144 if compilers.is_header(src):
1145 header_deps.append(raw_src)
1146 else:
1147 transpiled_source_files.append(raw_src)
1148 for src in transpiled_source_files:
1149 o, s = self.generate_single_compile(target, src, True, [], header_deps)
1150 obj_list.append(o)
1151
1152 # Generate compile targets for all the preexisting sources for this target
1153 for src in target_sources.values():
1154 if not compilers.is_separate_compile(src):
1155 continue
1156 if compilers.is_header(src) and not is_compile_target:
1157 continue
1158 if compilers.is_llvm_ir(src):
1159 o, s = self.generate_llvm_ir_compile(target, src)
1160 obj_list.append(o)
1161 elif is_unity and self.get_target_source_can_unity(target, src):
1162 unity_src.append(src)
1163 else:
1164 o, s = self.generate_single_compile(target, src, False, [],
1165 [*header_deps, *d_generated_deps, *fortran_order_deps],
1166 fortran_inc_args)
1167 obj_list.append(o)
1168 compiled_sources.append(s)
1169 source2object[s] = o
1170
1171 if is_unity:
1172 for src in self.generate_unity_files(target, unity_src):
1173 o, s = self.generate_single_compile(target, src, True, [*unity_deps, *header_deps, *d_generated_deps],
1174 fortran_order_deps, fortran_inc_args, unity_src)
1175 obj_list.append(o)
1176 compiled_sources.append(s)
1177 source2object[s] = o
1178 if is_compile_target:
1179 # Skip the link stage for this special type of target
1180 return
1181
1182 if not isinstance(target, build.StaticLibrary):
1183 final_obj_list = obj_list
1184 elif target.prelink:
1185 final_obj_list = self.generate_prelink(target, obj_list)
1186 else:
1187 final_obj_list = obj_list
1188
1189 self.generate_dependency_scan_target(target, compiled_sources, source2object, fortran_order_deps)
1190
1191 if isinstance(target, build.SharedLibrary):
1192 self.generate_shsym(target)
1193 if target.uses_rust():
1194 self.generate_rust_target(target, outname, final_obj_list, fortran_order_deps)
1195 return
1196
1197 linker, stdlib_args = self.determine_linker_and_stdlib_args(target)
1198 elem = self.generate_link(target, outname, final_obj_list, linker, pch_objects, stdlib_args=stdlib_args)
1199 self.add_build(elem)
1200 #In AIX, we archive shared libraries. If the instance is a shared library, we add a command to archive the shared library
1201 #object and create the build element.
1202 if isinstance(target, build.SharedLibrary) and self.environment.machines[target.for_machine].is_aix():
1203 if target.aix_so_archive:
1204 elem = NinjaBuildElement(self.all_outputs, linker.get_archive_name(outname), 'AIX_LINKER', [outname])
1205 self.add_build(elem)
1206
1207 def should_use_dyndeps_for_target(self, target: build.BuildTargetTypes) -> bool:
1208 if not self.ninja_has_dyndeps:
1209 return False
1210 if not isinstance(target, build.BuildTarget):
1211 return False
1212 if 'fortran' in target.compilers:
1213 return True
1214 if 'cpp' not in target.compilers:
1215 return False
1216 for arg in target.compilers['cpp'].get_cpp_modules_args():
1217 if arg in target.extra_args['cpp']:
1218 return True
1219 # Currently only the preview version of Visual Studio is supported.
1220 cpp = target.compilers['cpp']
1221 if cpp.get_id() != 'msvc':
1222 return False
1223 cppversion = self.get_target_option(target, OptionKey('cpp_std',
1224 machine=target.for_machine,
1225 subproject=target.subproject))
1226 if cppversion not in ('latest', 'c++latest', 'vc++latest'):
1227 return False
1228 if not mesonlib.current_vs_supports_modules():
1229 return False
1230 if mesonlib.version_compare(cpp.version, '<19.28.28617'):
1231 return False
1232 return True
1233
1234 def generate_dependency_scan_target(self, target: build.BuildTarget,
1235 compiled_sources: T.List[str],
1236 source2object: T.Dict[str, str],
1237 object_deps: T.List[File]) -> None:
1238 if not self.should_use_dyndeps_for_target(target):
1239 return
1240 self._uses_dyndeps = True
1241 json_file, depscan_file = self.get_dep_scan_file_for(target)
1242 pickle_base = target.name + '.dat'
1243 pickle_file = os.path.join(self.get_target_private_dir(target), pickle_base).replace('\\', '/')
1244 pickle_abs = os.path.join(self.get_target_private_dir_abs(target), pickle_base).replace('\\', '/')
1245 rule_name = 'depscan'
1246 scan_sources = list(self.select_sources_to_scan(compiled_sources))
1247
1248 scaninfo = TargetDependencyScannerInfo(
1249 self.get_target_private_dir(target), source2object, scan_sources)
1250
1251 write = True
1252 if os.path.exists(pickle_abs):
1253 with open(pickle_abs, 'rb') as p:
1254 old = pickle.load(p)
1255 write = old != scaninfo
1256
1257 if write:
1258 with open(pickle_abs, 'wb') as p:
1259 pickle.dump(scaninfo, p)
1260
1261 elem = NinjaBuildElement(self.all_outputs, json_file, rule_name, pickle_file)
1262 # A full dependency is required on all scanned sources, if any of them
1263 # are updated we need to rescan, as they may have changed the modules
1264 # they use or export.
1265 for s in scan_sources:
1266 elem.deps.add(s[0])
1267 elem.add_orderdep(self.order_deps_to_strings(target, object_deps))
1268 elem.add_item('name', target.name)
1269 self.add_build(elem)
1270
1271 infiles: T.Set[str] = set()
1272 for t in target.get_all_linked_targets():
1273 if self.should_use_dyndeps_for_target(t):
1274 assert isinstance(t, build.BuildTarget)
1275 infiles.add(self.get_dep_scan_file_for(t)[0])
1276 _, od = self.flatten_object_list(target)
1277 infiles.update({self.get_dep_scan_file_for(t)[0] for t in od if t.uses_fortran()})
1278
1279 elem = NinjaBuildElement(self.all_outputs, depscan_file, 'depaccumulate', [json_file] + sorted(infiles))
1280 elem.add_item('name', target.name)
1281 self.add_build(elem)
1282
1283 def select_sources_to_scan(self, compiled_sources: T.List[str],
1284 ) -> T.Iterable[T.Tuple[str, Literal['cpp', 'fortran']]]:
1285 # in practice pick up C++ and Fortran files. If some other language
1286 # requires scanning (possibly Java to deal with inner class files)
1287 # then add them here.
1288 for source in compiled_sources:
1289 if isinstance(source, mesonlib.File):
1290 source = source.rel_to_builddir(self.build_to_src)
1291 ext = os.path.splitext(source)[1][1:]
1292 if ext.lower() in compilers.lang_suffixes['cpp'] or ext == 'C':
1293 yield source, 'cpp'
1294 elif ext.lower() in compilers.lang_suffixes['fortran']:
1295 yield source, 'fortran'
1296
1297 def process_target_dependencies(self, target: build.BuildTarget) -> None:
1298 for t in target.get_dependencies():
1299 if t.get_id() not in self.processed_targets:
1300 self.generate_target(t.get_target())
1301
1302 def custom_target_generator_inputs(self, target: build.CustomTarget) -> None:
1303 for s in target.sources:
1304 if isinstance(s, build.GeneratedList):
1305 self.generate_genlist_for_target(s, target)
1306
1307 def generate_custom_target(self, target: build.CustomTarget) -> None:
1308 self.custom_target_generator_inputs(target)
1309 (srcs, ofilenames, cmd) = self.eval_custom_target_command(target)
1310 deps = self.get_paths_for_dep_outputs(target, target.get_dependencies())
1311 deps += self.get_target_depend_files(target)
1312 deps += self.get_paths_for_dep_outputs(target, target.extra_depends)
1313 if target.build_always_stale:
1314 deps.append('PHONY')
1315 if target.depfile_type == 'gcc':
1316 rulename = 'CUSTOM_COMMAND_DEP'
1317 elif target.depfile_type == 'msvc':
1318 rulename = 'CUSTOM_COMMAND_MSVC_DEP'
1319 else:
1320 rulename = 'CUSTOM_COMMAND'
1321 elem = NinjaBuildElement(self.all_outputs, ofilenames, rulename, srcs)
1322 elem.add_dep(deps)
1323
1324 cmd, reason = self.as_meson_exe_cmdline(target.command[0], cmd[1:],
1325 extra_bdeps=target.get_transitive_build_target_deps(),
1326 capture=ofilenames[0] if target.capture else None,
1327 feed=srcs[0] if target.feed else None,
1328 env=target.env,
1329 can_use_rsp_file=target.rspable,
1330 verbose=target.console)
1331 if reason:
1332 cmd_type = f' (wrapped by meson {reason})'
1333 else:
1334 cmd_type = ''
1335 if target.depfile is not None:
1336 depfile = target.get_dep_outname(elem.infilenames)
1337 rel_dfile = os.path.join(self.get_target_dir(target), depfile)
1338 abs_pdir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target))
1339 os.makedirs(abs_pdir, exist_ok=True)
1340 elem.add_item('DEPFILE', rel_dfile)
1341 if target.console:
1342 elem.add_item('pool', 'console')
1343 full_name = Path(target.subdir, target.name).as_posix()
1344 elem.add_item('COMMAND', cmd)
1345 elem.add_item('description', target.description.format(full_name) + cmd_type)
1346 self.add_build(elem)
1347 self.processed_targets.add(target.get_id())
1348
1349 def build_run_target_name(self, target: build.RunTarget) -> str:
1350 if target.subproject != '':
1351 subproject_prefix = f'{target.subproject}@@'
1352 else:
1353 subproject_prefix = ''
1354 return f'{subproject_prefix}{target.name}'
1355
1356 def generate_run_target(self, target: build.RunTarget) -> None:
1357 target_name = self.build_run_target_name(target)
1358 if not target.command:
1359 # This is an alias target, it has no command, it just depends on
1360 # other targets.
1361 elem = NinjaBuildElement(self.all_outputs, target_name, 'phony', [])
1362 else:
1363 target_env = self.get_run_target_env(target)
1364 _, _, cmd = self.eval_custom_target_command(target)
1365 meson_exe_cmd, reason = self.as_meson_exe_cmdline(target.command[0], cmd[1:],
1366 env=target_env,
1367 verbose=True)
1368 cmd_type = f' (wrapped by meson {reason})' if reason else ''
1369 elem = self.create_phony_target(target_name, 'CUSTOM_COMMAND', [])
1370 elem.add_item('COMMAND', meson_exe_cmd)
1371 elem.add_item('description', f'Running external command {target.name}{cmd_type}')
1372 elem.add_item('pool', 'console')
1373 deps = self.get_paths_for_dep_outputs(target, target.get_dependencies())
1374 deps += self.get_target_depend_files(target)
1375 elem.add_dep(deps)
1376 self.add_build(elem)
1377 self.processed_targets.add(target.get_id())
1378
1379 def generate_coverage_command(self, elem: NinjaBuildElement, outputs: T.List[str],
1380 gcovr_exe: T.Optional[str], llvm_cov_exe: T.Optional[str]) -> None:
1381 targets = self.build.get_targets().values()
1382 use_llvm_cov = False
1383 exe_args = []
1384 if gcovr_exe is not None:
1385 exe_args += ['--gcov', gcovr_exe]
1386 if llvm_cov_exe is not None:
1387 exe_args += ['--llvm-cov', llvm_cov_exe]
1388
1389 for target in targets:
1390 if not isinstance(target, build.BuildTarget):
1391 continue
1392 for compiler in target.compilers.values():
1393 if compiler.get_id() == 'clang' and not compiler.info.is_darwin():
1394 use_llvm_cov = True
1395 break
1396 elem.add_item('COMMAND', self.environment.get_build_command() +
1397 ['--internal', 'coverage'] +
1398 outputs +
1399 [self.environment.get_source_dir(),
1400 os.path.join(self.environment.get_source_dir(),
1401 self.build.get_subproject_dir()),
1402 self.environment.get_build_dir(),
1403 self.environment.get_log_dir()] +
1404 exe_args +
1405 (['--use-llvm-cov'] if use_llvm_cov else []))
1406
1407 def generate_coverage_rules(self, gcovr_exe: T.Optional[str], gcovr_version: T.Optional[str], llvm_cov_exe: T.Optional[str]) -> None:
1408 e = self.create_phony_target('coverage', 'CUSTOM_COMMAND', 'PHONY')
1409 self.generate_coverage_command(e, [], gcovr_exe, llvm_cov_exe)
1410 e.add_item('description', 'Generating coverage reports')
1411 self.add_build(e)
1412 self.generate_coverage_legacy_rules(gcovr_exe, gcovr_version, llvm_cov_exe)
1413
1414 def generate_coverage_legacy_rules(self, gcovr_exe: T.Optional[str], gcovr_version: T.Optional[str], llvm_cov_exe: T.Optional[str]) -> None:
1415 e = self.create_phony_target('coverage-html', 'CUSTOM_COMMAND', 'PHONY')
1416 self.generate_coverage_command(e, ['--html'], gcovr_exe, llvm_cov_exe)
1417 e.add_item('description', 'Generating HTML coverage report')
1418 self.add_build(e)
1419
1420 if gcovr_exe:
1421 e = self.create_phony_target('coverage-xml', 'CUSTOM_COMMAND', 'PHONY')
1422 self.generate_coverage_command(e, ['--xml'], gcovr_exe, llvm_cov_exe)
1423 e.add_item('description', 'Generating XML coverage report')
1424 self.add_build(e)
1425
1426 e = self.create_phony_target('coverage-text', 'CUSTOM_COMMAND', 'PHONY')
1427 self.generate_coverage_command(e, ['--text'], gcovr_exe, llvm_cov_exe)
1428 e.add_item('description', 'Generating text coverage report')
1429 self.add_build(e)
1430
1431 if mesonlib.version_compare(gcovr_version, '>=4.2'):
1432 e = self.create_phony_target('coverage-sonarqube', 'CUSTOM_COMMAND', 'PHONY')
1433 self.generate_coverage_command(e, ['--sonarqube'], gcovr_exe, llvm_cov_exe)
1434 e.add_item('description', 'Generating Sonarqube XML coverage report')
1435 self.add_build(e)
1436
1437 def generate_install(self) -> None:
1438 self.create_install_data_files()
1439 elem = self.create_phony_target('install', 'CUSTOM_COMMAND', 'PHONY')
1440 elem.add_dep('all')
1441 elem.add_item('DESC', 'Installing files')
1442 elem.add_item('COMMAND', self.environment.get_build_command() + ['install', '--no-rebuild'])
1443 elem.add_item('pool', 'console')
1444 self.add_build(elem)
1445
1446 def generate_tests(self) -> None:
1447 self.serialize_tests()
1448 cmd = self.environment.get_build_command(True) + ['test', '--no-rebuild']
1449 if not self.environment.coredata.optstore.get_value_for(OptionKey('stdsplit')):
1450 cmd += ['--no-stdsplit']
1451 if self.environment.coredata.optstore.get_value_for(OptionKey('errorlogs')):
1452 cmd += ['--print-errorlogs']
1453 elem = self.create_phony_target('test', 'CUSTOM_COMMAND', ['all', 'meson-test-prereq', 'PHONY'])
1454 elem.add_item('COMMAND', cmd)
1455 elem.add_item('DESC', 'Running all tests')
1456 elem.add_item('pool', 'console')
1457 self.add_build(elem)
1458
1459 # And then benchmarks.
1460 cmd = self.environment.get_build_command(True) + [
1461 'test', '--benchmark', '--logbase',
1462 'benchmarklog', '--num-processes=1', '--no-rebuild']
1463 elem = self.create_phony_target('benchmark', 'CUSTOM_COMMAND', ['all', 'meson-benchmark-prereq', 'PHONY'])
1464 elem.add_item('COMMAND', cmd)
1465 elem.add_item('DESC', 'Running benchmark suite')
1466 elem.add_item('pool', 'console')
1467 self.add_build(elem)
1468
1469 def generate_rules(self) -> None:
1470 self.add_rule_comment(NinjaComment('Rules for module scanning.'))
1471 self.generate_scanner_rules()
1472 self.add_rule_comment(NinjaComment('Rules for compiling.'))
1473 self.generate_compile_rules()
1474 self.add_rule_comment(NinjaComment('Rules for linking.'))
1475 self.generate_static_link_rules()
1476 self.generate_dynamic_link_rules()
1477 self.add_rule_comment(NinjaComment('Other rules'))
1478
1479 # Ninja errors out if you have deps = gcc but no depfile, so we must
1480 # have two rules for custom commands.
1481 self.add_rule(NinjaRule('CUSTOM_COMMAND', ['$COMMAND'], [], '$DESC',
1482 restat=True))
1483 self.add_rule(NinjaRule('CUSTOM_COMMAND_DEP', ['$COMMAND'], [], '$DESC',
1484 deps='gcc', depfile='$DEPFILE',
1485 restat=True))
1486 self.add_rule(NinjaRule('CUSTOM_COMMAND_MSVC_DEP', ['$COMMAND'], [], '$DESC',
1487 deps='msvc',
1488 restat=True))
1489 self.add_rule(NinjaRule('COPY_FILE', self.environment.get_build_command() + ['--internal', 'copy'],
1490 ['$in', '$out'], 'Copying $in to $out'))
1491
1492 c = self.environment.get_build_command() + \
1493 ['--internal',
1494 'regenerate',
1495 self.environment.get_source_dir(),
1496 # Ninja always runs from the build_dir. This includes cases where the user moved the
1497 # build directory and invalidated most references. Make sure it still regenerates.
1498 '.']
1499 self.add_rule(NinjaRule('REGENERATE_BUILD',
1500 c, [],
1501 'Regenerating build files',
1502 extra='generator = 1'))
1503
1504 def add_rule_comment(self, comment: NinjaComment) -> None:
1505 self.ninja.add_rule_comment(comment)
1506
1507 def add_build_comment(self, comment: NinjaComment) -> None:
1508 self.ninja.add_build_comment(comment)
1509
1510 def add_rule(self, rule: NinjaRule) -> None:
1511 self.ninja.add_rule(rule)
1512
1513 def add_build(self, build: NinjaBuildElement) -> None:
1514 self.ninja.add_build(build)
1515
1516 def generate_phony(self) -> None:
1517 self.add_build_comment(NinjaComment('Phony build target, always out of date'))
1518 elem = NinjaBuildElement(self.all_outputs, 'PHONY', 'phony', '')
1519 self.add_build(elem)
1520
1521 def generate_jar_target(self, target: build.Jar) -> None:
1522 fname = target.get_filename()
1523 outname_rel = os.path.join(self.get_target_dir(target), fname)
1524 src_list = target.get_sources()
1525 resources = target.get_java_resources()
1526 compiler = target.compilers['java']
1527 c = 'c'
1528 m = 'm'
1529 e = ''
1530 f = 'f'
1531 main_class = target.get_main_class()
1532 if main_class != '':
1533 e = 'e'
1534
1535 # Add possible java generated files to src list
1536 generated_sources = self.get_target_generated_sources(target)
1537 gen_src_list = []
1538 for rel_src in generated_sources:
1539 raw_src = File.from_built_relative(rel_src)
1540 if rel_src.endswith('.java'):
1541 gen_src_list.append(raw_src)
1542
1543 compile_args = self.determine_java_compile_args(target, compiler)
1544 class_list = self.generate_java_compile([*src_list, *gen_src_list], target, compiler, compile_args)
1545 class_dep_list = [os.path.join(self.get_target_private_dir(target), i) for i in class_list]
1546 manifest_path = os.path.join(self.get_target_private_dir(target), 'META-INF', 'MANIFEST.MF')
1547 manifest_fullpath = os.path.join(self.environment.get_build_dir(), manifest_path)
1548 os.makedirs(os.path.dirname(manifest_fullpath), exist_ok=True)
1549 with open(manifest_fullpath, 'w', encoding='utf-8') as manifest:
1550 if any(target.link_targets):
1551 manifest.write('Class-Path: ')
1552 cp_paths = [os.path.join(self.get_target_dir(l), l.get_filename()) for l in target.link_targets]
1553 manifest.write(' '.join(cp_paths))
1554 manifest.write('\n')
1555 jar_rule = 'java_LINKER'
1556 commands = [c + m + e + f]
1557 commands.append(manifest_path)
1558 if e != '':
1559 commands.append(main_class)
1560 commands.append(self.get_target_filename(target))
1561 # Java compilation can produce an arbitrary number of output
1562 # class files for a single source file. Thus tell jar to just
1563 # grab everything in the final package.
1564 commands += ['-C', self.get_target_private_dir(target), '.']
1565 elem = NinjaBuildElement(self.all_outputs, outname_rel, jar_rule, [])
1566 elem.add_dep(class_dep_list)
1567 if resources:
1568 # Copy all resources into the root of the jar.
1569 elem.add_orderdep(self.__generate_sources_structure(Path(self.get_target_private_dir(target)), resources)[0])
1570 elem.add_item('ARGS', commands)
1571 self.add_build(elem)
1572 # Create introspection information
1573 self.create_target_source_introspection(target, compiler, compile_args, src_list, gen_src_list)
1574
1575 def generate_cs_resource_tasks(self, target: build.BuildTarget) -> T.Tuple[T.List[str], T.List[str]]:
1576 args = []
1577 deps = []
1578 for r in target.resources:
1579 rel_sourcefile = os.path.join(self.build_to_src, target.subdir, r)
1580 if r.endswith('.resources'):
1581 a = '-resource:' + rel_sourcefile
1582 elif r.endswith('.txt') or r.endswith('.resx'):
1583 ofilebase = os.path.splitext(os.path.basename(r))[0] + '.resources'
1584 ofilename = os.path.join(self.get_target_private_dir(target), ofilebase)
1585 elem = NinjaBuildElement(self.all_outputs, ofilename, "CUSTOM_COMMAND", rel_sourcefile)
1586 elem.add_item('COMMAND', ['resgen', rel_sourcefile, ofilename])
1587 elem.add_item('DESC', f'Compiling resource {rel_sourcefile}')
1588 self.add_build(elem)
1589 deps.append(ofilename)
1590 a = '-resource:' + ofilename
1591 else:
1592 raise InvalidArguments(f'Unknown resource file {r}.')
1593 args.append(a)
1594 return args, deps
1595
1596 def generate_cs_target(self, target: build.BuildTarget) -> None:
1597 fname = target.get_filename()
1598 outname_rel = os.path.join(self.get_target_dir(target), fname)
1599 src_list = target.get_sources()
1600 compiler = T.cast('CsCompiler', target.compilers['cs'])
1601 rel_srcs = [os.path.normpath(s.rel_to_builddir(self.build_to_src)) for s in src_list]
1602 deps = []
1603 commands = self.generate_basic_compiler_args(target, compiler)
1604 commands += target.extra_args['cs']
1605 if isinstance(target, build.Executable):
1606 commands.append('-target:exe')
1607 elif isinstance(target, build.SharedLibrary):
1608 commands.append('-target:library')
1609 else:
1610 raise MesonException('Unknown C# target type.')
1611 (resource_args, resource_deps) = self.generate_cs_resource_tasks(target)
1612 commands += resource_args
1613 deps += resource_deps
1614 commands += compiler.get_output_args(outname_rel)
1615 for l in target.link_targets:
1616 lname = os.path.join(self.get_target_dir(l), l.get_filename())
1617 commands += compiler.get_link_args(lname)
1618 deps.append(lname)
1619 if '-g' in commands:
1620 outputs = [outname_rel, outname_rel + '.mdb']
1621 else:
1622 outputs = [outname_rel]
1623 generated_sources = self.get_target_generated_sources(target)
1624 generated_rel_srcs = []
1625 for rel_src in generated_sources:
1626 if rel_src.lower().endswith('.cs'):
1627 generated_rel_srcs.append(os.path.normpath(rel_src))
1628 deps.append(os.path.normpath(rel_src))
1629
1630 for dep in target.get_external_deps():
1631 commands.extend_direct(dep.get_link_args())
1632
1633 elem = NinjaBuildElement(self.all_outputs, outputs, self.compiler_to_rule_name(compiler), rel_srcs + generated_rel_srcs)
1634 elem.add_dep(deps)
1635 elem.add_item('ARGS', commands)
1636 self.add_build(elem)
1637
1638 self.create_target_source_introspection(target, compiler, commands, rel_srcs, generated_rel_srcs)
1639
1640 def determine_java_compile_args(self, target: build.Jar, compiler: Compiler) -> T.List[str]:
1641 args = self.generate_basic_compiler_args(target, compiler)
1642 args += target.get_java_args()
1643 args += compiler.get_output_args(self.get_target_private_dir(target))
1644 args += target.get_classpath_args()
1645 curdir = target.get_subdir()
1646 sourcepaths = [os.path.join(self.build_to_src, curdir)]
1647 sourcepaths.append(os.path.normpath(curdir))
1648 for i in target.include_dirs:
1649 sourcepaths.extend(i.abs_string_list(self.source_dir, self.build_dir))
1650 args += ['-sourcepath', os.pathsep.join(sourcepaths)]
1651 return list(args)
1652
1653 def generate_java_compile(self, srcs: T.List[File], target: build.BuildTarget, compiler: Compiler, args: T.List[str]) -> T.List[str]:
1654 deps = [os.path.join(self.get_target_dir(l), l.get_filename()) for l in target.link_targets]
1655 generated_sources = self.get_target_generated_sources(target)
1656 for rel_src in generated_sources:
1657 if rel_src.endswith('.java'):
1658 deps.append(rel_src)
1659
1660 rel_srcs = []
1661 plain_class_paths = []
1662 rel_objs = []
1663 for src in srcs:
1664 rel_src = src.rel_to_builddir(self.build_to_src)
1665 rel_srcs.append(rel_src)
1666
1667 # Preserve any additional path components on top of the target's subdir
1668 plain_class_path = os.path.relpath(src.relative_name(), target.get_subdir())
1669 plain_class_path = plain_class_path[:-4] + 'class'
1670 plain_class_paths.append(plain_class_path)
1671 rel_obj = os.path.join(self.get_target_private_dir(target), plain_class_path)
1672 rel_objs.append(rel_obj)
1673 element = NinjaBuildElement(self.all_outputs, rel_objs, self.compiler_to_rule_name(compiler), rel_srcs)
1674 element.add_dep(deps)
1675 element.add_item('ARGS', args)
1676 element.add_item('FOR_JAR', self.get_target_filename(target))
1677 self.add_build(element)
1678 return plain_class_paths
1679
1680 def generate_java_link(self) -> None:
1681 rule = 'java_LINKER'
1682 command = ['jar', '$ARGS']
1683 description = 'Creating JAR $out'
1684 self.add_rule(NinjaRule(rule, command, [], description))
1685
1686 def determine_dep_vapis(self, target: build.BuildTarget) -> T.List[str]:
1687 """
1688 Peek into the sources of BuildTargets we're linking with, and if any of
1689 them was built with Vala, assume that it also generated a .vapi file of
1690 the same name as the BuildTarget and return the path to it relative to
1691 the build directory.
1692 """
1693 result: OrderedSet[str] = OrderedSet()
1694 for dep in itertools.chain(target.link_targets, target.link_whole_targets):
1695 if not (isinstance(dep, build.BuildTarget) and dep.is_linkable_target()):
1696 continue
1697 for i in dep.sources:
1698 if i.split('.')[-1] in compilers.lang_suffixes['vala']:
1699 if dep.vala_vapi is not None:
1700 vapiname = dep.vala_vapi
1701 fullname = os.path.join(self.get_target_dir(dep), vapiname)
1702 result.add(fullname)
1703 break
1704 return list(result)
1705
1706 def split_vala_sources(self, t: build.BuildTarget) -> \
1707 T.Tuple[T.MutableMapping[str, build.TargetSources], T.MutableMapping[str, build.TargetSources],
1708 T.MutableMapping[str, File], T.MutableMapping[str, build.TargetSources]]:
1709 """
1710 Splits the target's sources into .vala, .gs, .vapi, and other sources.
1711 Handles both preexisting and generated sources.
1712
1713 Returns a tuple (vala, vapi, others) each of which is a dictionary with
1714 the keys being the path to the file (relative to the build directory)
1715 and the value being the object that generated or represents the file.
1716 """
1717 vala: T.MutableMapping[str, build.TargetSources] = OrderedDict()
1718 vapi: T.MutableMapping[str, build.TargetSources] = OrderedDict()
1719 others: T.MutableMapping[str, File] = OrderedDict()
1720 othersgen: T.MutableMapping[str, build.TargetSources] = OrderedDict()
1721 # Split preexisting sources
1722 for s in t.get_sources():
1723 # BuildTarget sources are always mesonlib.File files which are
1724 # either in the source root, or generated with configure_file and
1725 # in the build root
1726 if not isinstance(s, File):
1727 raise InvalidArguments(f'All sources in target {t!r} must be of type mesonlib.File, not {s!r}')
1728 f = s.rel_to_builddir(self.build_to_src)
1729 if s.endswith(('.vala', '.gs')):
1730 vala[f] = s
1731 elif s.endswith('.vapi'):
1732 vapi[f] = s
1733 else:
1734 others[f] = s
1735 # Split generated sources
1736 for gensrc in t.get_generated_sources():
1737 for s in gensrc.get_outputs():
1738 f = self.get_target_generated_dir(t, gensrc, s)
1739 if s.endswith(('.vala', '.gs')):
1740 gensrctype = vala
1741 elif s.endswith('.vapi'):
1742 gensrctype = vapi
1743 # Generated non-Vala (C/C++) sources. Won't be used for
1744 # generating the Vala compile rule below.
1745 else:
1746 gensrctype = othersgen
1747 # Duplicate outputs are disastrous
1748 if f in gensrctype and gensrctype[f] != gensrc:
1749 msg = 'Duplicate output {0!r} from {1!r} {2!r}; ' \
1750 'conflicts with {0!r} from {4!r} {3!r}' \
1751 ''.format(f, type(gensrc).__name__, gensrc.name,
1752 gensrctype[f], type(gensrctype[f]).__name__)
1753 raise InvalidArguments(msg)
1754 # Store 'somefile.vala': GeneratedList (or CustomTarget)
1755 gensrctype[f] = gensrc
1756 return vala, vapi, others, othersgen
1757
1758 def generate_vala_compile(self, target: build.BuildTarget) -> \
1759 T.Tuple[T.MutableMapping[str, File], T.MutableMapping[str, build.TargetSources], T.List[str]]:
1760 """Vala is compiled into C. Set up all necessary build steps here."""
1761 (vala_src, vapi_src, others, othersgen) = self.split_vala_sources(target)
1762 extra_dep_files = []
1763 if not vala_src:
1764 raise InvalidArguments(f'Vala library {target.name!r} has no Vala or Genie source files.')
1765
1766 valac = target.compilers['vala']
1767 c_out_dir = self.get_target_private_dir(target)
1768 # C files generated by valac
1769 vala_c_src: T.List[str] = []
1770 # Files generated by valac
1771 valac_outputs: T.List = []
1772 # All sources that are passed to valac on the commandline
1773 all_files = list(vapi_src)
1774 # Passed as --basedir
1775 srcbasedir = os.path.join(self.build_to_src, target.get_subdir())
1776 for (vala_file, gensrc) in vala_src.items():
1777 all_files.append(vala_file)
1778 # Figure out where the Vala compiler will write the compiled C file
1779 #
1780 # If the Vala file is in a subdir of the build dir (in our case
1781 # because it was generated/built by something else), and is also
1782 # a subdir of --basedir (because the builddir is in the source
1783 # tree, and the target subdir is the source root), the subdir
1784 # components from the source root till the private builddir will be
1785 # duplicated inside the private builddir. Otherwise, just the
1786 # basename will be used.
1787 #
1788 # If the Vala file is outside the build directory, the paths from
1789 # the --basedir till the subdir will be duplicated inside the
1790 # private builddir.
1791 if isinstance(gensrc, (build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)) or gensrc.is_built:
1792 vala_c_file = os.path.splitext(os.path.basename(vala_file))[0] + '.c'
1793 # Check if the vala file is in a subdir of --basedir
1794 abs_srcbasedir = os.path.join(self.environment.get_source_dir(), target.get_subdir())
1795 abs_vala_file = os.path.join(self.environment.get_build_dir(), vala_file)
1796 if is_parent_path(abs_srcbasedir, abs_vala_file):
1797 vala_c_subdir = PurePath(abs_vala_file).parent.relative_to(abs_srcbasedir)
1798 vala_c_file = os.path.join(str(vala_c_subdir), vala_c_file)
1799 else:
1800 path_to_target = os.path.join(self.build_to_src, target.get_subdir())
1801 if vala_file.startswith(path_to_target):
1802 vala_c_file = os.path.splitext(os.path.relpath(vala_file, path_to_target))[0] + '.c'
1803 else:
1804 vala_c_file = os.path.splitext(os.path.basename(vala_file))[0] + '.c'
1805 # All this will be placed inside the c_out_dir
1806 vala_c_file = os.path.join(c_out_dir, vala_c_file)
1807 vala_c_src.append(vala_c_file)
1808 valac_outputs.append(vala_c_file)
1809
1810 args = self.generate_basic_compiler_args(target, valac)
1811 b_colorout = self.get_target_option(target, 'b_colorout')
1812 assert isinstance(b_colorout, str)
1813 args += valac.get_colorout_args(b_colorout)
1814 # Tell Valac to output everything in our private directory. Sadly this
1815 # means it will also preserve the directory components of Vala sources
1816 # found inside the build tree (generated sources).
1817 args += ['--directory', c_out_dir]
1818 args += ['--basedir', srcbasedir]
1819 if target.is_linkable_target():
1820 assert isinstance(target, build.LinkableTarget)
1821 # Library name
1822 args += ['--library', target.name]
1823 # Outputted header
1824 if target.vala_header is not None:
1825 hname = os.path.join(self.get_target_dir(target), target.vala_header)
1826 args += ['--header', hname]
1827 if self.is_unity(target):
1828 # Without this the declarations will get duplicated in the .c
1829 # files and cause a build failure when all of them are
1830 # #include-d in one .c file.
1831 # https://github.com/mesonbuild/meson/issues/1969
1832 args += ['--use-header']
1833 valac_outputs.append(hname)
1834 # Outputted vapi file
1835 if target.vala_vapi is not None:
1836 vapiname = os.path.join(self.get_target_dir(target), target.vala_vapi)
1837 # Force valac to write the vapi and gir files in the target build dir.
1838 # Without this, it will write it inside c_out_dir
1839 args += ['--vapi', os.path.join('..', target.vala_vapi)]
1840 valac_outputs.append(vapiname)
1841 # Generate GIR if requested
1842 if target.vala_gir is not None:
1843 girname = os.path.join(self.get_target_dir(target), target.vala_gir)
1844 args += ['--gir', os.path.join('..', target.vala_gir)]
1845 valac_outputs.append(girname)
1846 shared_target = target.get('shared')
1847 if isinstance(shared_target, build.SharedLibrary):
1848 args += ['--shared-library', shared_target.get_filename()]
1849 # Detect gresources and add --gresources/--gresourcesdir arguments for each
1850 gres_dirs = []
1851 for gensrc in othersgen.values():
1852 if isinstance(gensrc, modules.GResourceTarget):
1853 gres_xml, = self.get_custom_target_sources(gensrc)
1854 args += ['--gresources=' + gres_xml]
1855 for source_dir in gensrc.source_dirs:
1856 gres_dirs += [source_dir]
1857 # Ensure that resources are built before vala sources
1858 # This is required since vala code using [GtkTemplate] effectively depends on .ui files
1859 # GResourceHeaderTarget is not suitable due to lacking depfile
1860 gres_c, = gensrc.get_outputs()
1861 extra_dep_files += [os.path.join(self.get_target_dir(gensrc), gres_c)]
1862 for gres_dir in OrderedSet(gres_dirs):
1863 args += [f'--gresourcesdir={gres_dir}']
1864 dependency_vapis = self.determine_dep_vapis(target)
1865 extra_dep_files += dependency_vapis
1866 extra_dep_files.extend(self.get_target_depend_files(target))
1867 args += target.get_extra_args('vala')
1868 element = NinjaBuildElement(self.all_outputs, valac_outputs,
1869 self.compiler_to_rule_name(valac),
1870 all_files + dependency_vapis)
1871 element.add_item('ARGS', args)
1872 depfile = valac.depfile_for_object(os.path.join(self.get_target_dir(target), target.name))
1873 element.add_item('DEPFILE', depfile)
1874 element.add_dep(extra_dep_files)
1875 self.add_build(element)
1876 self.create_target_source_introspection(target, valac, args, all_files, [])
1877 return others, othersgen, vala_c_src
1878
1879 def generate_cython_transpile(self, target: build.BuildTarget) -> \
1880 T.Tuple[T.MutableMapping[str, File], T.MutableMapping[str, build.TargetSources], T.List[str]]:
1881 """Generate rules for transpiling Cython files to C or C++"""
1882
1883 static_sources: T.MutableMapping[str, File] = OrderedDict()
1884 generated_sources: T.MutableMapping[str, build.TargetSources] = OrderedDict()
1885 cython_sources: T.List[str] = []
1886
1887 cython = target.compilers['cython']
1888
1889 args: T.List[str] = []
1890 args += cython.get_always_args()
1891 debug = self.get_target_option(target, 'debug')
1892 assert isinstance(debug, bool)
1893 args += cython.get_debug_args(debug)
1894 optimization = self.get_target_option(target, 'optimization')
1895 assert isinstance(optimization, str)
1896 args += cython.get_optimization_args(optimization)
1897 args += cython.get_option_compile_args(target, target.subproject)
1898 args += cython.get_option_std_args(target, target.subproject)
1899 args += self.build.get_global_args(cython, target)
1900 args += self.build.get_project_args(cython, target)
1901 args += target.get_extra_args('cython')
1902
1903 ext = self.get_target_option(target, OptionKey('cython_language', machine=target.for_machine))
1904
1905 pyx_sources = [] # Keep track of sources we're adding to build
1906 pyx_count = 0
1907 for src in target.get_sources():
1908 if src.endswith('.pyx'):
1909 pyx_count += 1
1910 for gen in target.get_generated_sources():
1911 for ssrc in gen.get_outputs():
1912 if ssrc.endswith('.pyx'):
1913 pyx_count += 1
1914
1915 for src in target.get_sources():
1916 if src.endswith('.pyx'):
1917 # Use basename to avoid too nested targets which can cause a
1918 # problem with MAX_PATH on Windows
1919 outname = os.path.basename(src.fname) if pyx_count == 1 else src.fname
1920 output = os.path.join(self.get_target_private_dir(target), f'{outname}.{ext}')
1921 element = NinjaBuildElement(
1922 self.all_outputs, [output],
1923 self.compiler_to_rule_name(cython),
1924 [src.absolute_path(self.environment.get_source_dir(), self.environment.get_build_dir())])
1925 element.add_item('ARGS', args)
1926 self.add_build(element)
1927 # TODO: introspection?
1928 cython_sources.append(output)
1929 pyx_sources.append(element)
1930 else:
1931 static_sources[src.rel_to_builddir(self.build_to_src)] = src
1932
1933 header_deps = [] # Keep track of generated headers for those sources
1934 for gen in target.get_generated_sources():
1935 if isinstance(gen, GeneratedList):
1936 builddir = self.get_target_private_dir(target)
1937 else:
1938 builddir = self.get_target_dir(gen)
1939 for ssrc in gen.get_outputs():
1940 ssrc = os.path.join(builddir, ssrc)
1941 if ssrc.endswith('.pyx'):
1942 # Use basename to avoid too nested targets which can cause
1943 # a problem with MAX_PATH on Windows
1944 outname = os.path.basename(ssrc) if pyx_count == 1 else ssrc
1945 output = os.path.join(self.get_target_private_dir(target), f'{outname}.{ext}')
1946 element = NinjaBuildElement(
1947 self.all_outputs, [output],
1948 self.compiler_to_rule_name(cython),
1949 [ssrc])
1950 element.add_item('ARGS', args)
1951 self.add_build(element)
1952 pyx_sources.append(element)
1953 # TODO: introspection?
1954 cython_sources.append(output)
1955 else:
1956 generated_sources[ssrc] = mesonlib.File.from_built_file(builddir, ssrc)
1957 # Following logic in L883-900 where we determine whether to add generated source
1958 # as a header(order-only) dep to the .so compilation rule
1959 if not compilers.is_source(ssrc) and \
1960 not compilers.is_object(ssrc) and \
1961 not compilers.is_library(ssrc) and \
1962 not modules.is_module_library(ssrc):
1963 header_deps.append(ssrc)
1964 for source in pyx_sources:
1965 source.add_orderdep(header_deps)
1966
1967 return static_sources, generated_sources, cython_sources
1968
1969 def _generate_copy_target(self, src: FileOrString, output: Path) -> None:
1970 """Create a target to copy a source file from one location to another."""
1971 if isinstance(src, File):
1972 instr = src.absolute_path(self.environment.source_dir, self.environment.build_dir)
1973 else:
1974 instr = src
1975 elem = NinjaBuildElement(self.all_outputs, [str(output)], 'COPY_FILE', [instr])
1976 elem.add_orderdep(instr)
1977 self.add_build(elem)
1978
1979 def __generate_sources_structure(self, root: Path, structured_sources: build.StructuredSources,
1980 main_file_ext: T.Union[str, T.Tuple[str, ...]] = tuple(),
1981 ) -> T.Tuple[T.List[str], T.Optional[str]]:
1982 first_file: T.Optional[str] = None
1983 orderdeps: T.List[str] = []
1984 for path, files in structured_sources.sources.items():
1985 for file in files:
1986 if isinstance(file, File):
1987 out = root / path / Path(file.fname).name
1988 self._generate_copy_target(file, out)
1989 out_s = str(out)
1990 orderdeps.append(out_s)
1991 if first_file is None and out_s.endswith(main_file_ext):
1992 first_file = out_s
1993 else:
1994 for f in file.get_outputs():
1995 out = root / path / f
1996 out_s = str(out)
1997 orderdeps.append(out_s)
1998 self._generate_copy_target(str(Path(file.subdir) / f), out)
1999 if first_file is None and out_s.endswith(main_file_ext):
2000 first_file = out_s
2001 return orderdeps, first_file
2002
2003 def _add_rust_project_entry(self, name: str, main_rust_file: str, args: CompilerArgs,
2004 crate_type: str, target_name: str,
2005 from_subproject: bool, proc_macro_dylib_path: T.Optional[str],
2006 deps: T.List[RustDep]) -> None:
2007 raw_edition: T.Optional[str] = mesonlib.first(reversed(args), lambda x: x.startswith('--edition'))
2008 edition = '2015' if not raw_edition else raw_edition.split('=', 1)[-1]
2009
2010 cfg: T.List[str] = []
2011 arg_itr: T.Iterator[str] = iter(args)
2012 for arg in arg_itr:
2013 if arg == '--cfg':
2014 cfg.append(next(arg_itr))
2015 elif arg.startswith('--cfg'):
2016 cfg.append(arg[len('--cfg'):])
2017
2018 crate = RustCrate(
2019 len(self.rust_crates),
2020 self._get_rust_crate_name(name),
2021 main_rust_file,
2022 crate_type,
2023 target_name,
2024 T.cast('RUST_EDITIONS', edition),
2025 deps,
2026 cfg,
2027 is_workspace_member=not from_subproject,
2028 proc_macro_dylib_path=proc_macro_dylib_path,
2029 )
2030
2031 self.rust_crates[name] = crate
2032
2033 @staticmethod
2034 def _get_rust_crate_name(target_name: str) -> str:
2035 # Rustc replaces - with _. spaces or dots are not allowed, so we replace them with underscores
2036 # Also +SUFFIX is dropped, which can be used to distinguish host from build crates
2037 crate_name = target_name.replace('-', '_').replace(' ', '_').replace('.', '_')
2038 return crate_name.split('+', 1)[0]
2039
2040 @staticmethod
2041 def _get_rust_dependency_name(target: build.BuildTarget, dependency: build.BuildTarget) -> str:
2042 crate_name_raw = target.rust_dependency_map.get(dependency.name, None)
2043 if crate_name_raw is None:
2044 dependency_crate_name = NinjaBackend._get_rust_crate_name(dependency.name)
2045 crate_name_raw = target.rust_dependency_map.get(dependency_crate_name, dependency.name)
2046 return NinjaBackend._get_rust_crate_name(crate_name_raw)
2047
2048 def generate_rust_sources(self, target: build.BuildTarget) -> T.Tuple[T.List[str], str]:
2049 orderdeps: T.List[str] = []
2050
2051 # Rust compiler takes only the main file as input and
2052 # figures out what other files are needed via import
2053 # statements and magic.
2054 main_rust_file: T.Optional[str] = None
2055 if target.structured_sources:
2056 if target.structured_sources.needs_copy():
2057 _ods, main_rust_file = self.__generate_sources_structure(Path(
2058 self.get_target_private_dir(target)) / 'structured', target.structured_sources, '.rs')
2059 if main_rust_file is None:
2060 raise MesonException('Could not find a rust file to treat as the main file for ', target.name)
2061 else:
2062 # The only way to get here is to have only files in the "root"
2063 # positional argument, which are all generated into the same
2064 # directory
2065 for g in target.structured_sources.sources['']:
2066 if isinstance(g, File):
2067 if g.endswith('.rs'):
2068 main_rust_file = g.rel_to_builddir(self.build_to_src)
2069 elif isinstance(g, GeneratedList):
2070 for h in g.get_outputs():
2071 if h.endswith('.rs'):
2072 main_rust_file = os.path.join(self.get_target_private_dir(target), h)
2073 break
2074 else:
2075 for h in g.get_outputs():
2076 if h.endswith('.rs'):
2077 main_rust_file = os.path.join(g.get_builddir(), h)
2078 break
2079 if main_rust_file is not None:
2080 break
2081
2082 _ods = []
2083 for f in target.structured_sources.as_list():
2084 if isinstance(f, File):
2085 _ods.append(f.rel_to_builddir(self.build_to_src))
2086 else:
2087 _ods.extend([os.path.join(self.build_to_src, f.subdir, s)
2088 for s in f.get_outputs()])
2089 self.all_structured_sources.update(_ods)
2090 orderdeps.extend(_ods)
2091 return orderdeps, main_rust_file
2092
2093 for i in target.get_sources():
2094 if main_rust_file is None and i.endswith('.rs'):
2095 main_rust_file = i.rel_to_builddir(self.build_to_src)
2096 for g in target.get_generated_sources():
2097 for i in g.get_outputs():
2098 if isinstance(g, GeneratedList):
2099 fname = os.path.join(self.get_target_private_dir(target), i)
2100 else:
2101 fname = os.path.join(g.get_builddir(), i)
2102 if main_rust_file is None and fname.endswith('.rs'):
2103 main_rust_file = fname
2104 orderdeps.append(fname)
2105
2106 return orderdeps, main_rust_file
2107
2108 def get_rust_compiler_args(self, target: build.BuildTarget, rustc: RustCompiler, src_crate_type: str,
2109 depfile: T.Optional[str] = None) -> CompilerArgs:
2110 # Compiler args for compiling this target
2111 args = compilers.get_base_compile_args(target, rustc, self.environment)
2112
2113 target_name = self.get_target_filename(target)
2114 args.extend(['--crate-type', src_crate_type])
2115
2116 # If we're dynamically linking, add those arguments
2117 if target.rust_crate_type in {'bin', 'dylib', 'cdylib'}:
2118 args.extend(rustc.get_linker_always_args())
2119 args += compilers.get_base_link_args(target, rustc, self.environment)
2120
2121 args += self.get_target_type_link_args(target, rustc)
2122
2123 if target.rust_crate_type in {'bin', 'dylib', 'cdylib'}:
2124 args += rustc.get_build_link_args(target, self.build)
2125 args += rustc.get_target_link_args(target)
2126
2127 cargs = args + self.generate_basic_compiler_args(target, rustc)
2128 cargs += ['--crate-name', self._get_rust_crate_name(target.name)]
2129 if depfile:
2130 cargs += rustc.get_dependency_gen_args(target_name, depfile)
2131 cargs += rustc.get_output_args(target_name)
2132 cargs += ['-C', 'metadata=' + target.get_id()]
2133 cargs += target.get_extra_args('rust')
2134 return cargs
2135
2136 def get_rust_compiler_deps_and_args(self, target: build.BuildTarget, rustc: RustCompiler,
2137 obj_list: T.List[str]) -> T.Tuple[T.List[str], T.List[RustDep], T.List[str]]:
2138 deps: T.List[str] = []
2139 project_deps: T.List[RustDep] = []
2140 args: T.List[str] = []
2141
2142 def _link_library(libname: str, static: bool, bundle: bool = False) -> None:
2143 orig_libname = libname
2144 type_ = 'static' if static else 'dylib'
2145 modifiers = []
2146 # Except with -Clink-arg, search is limited to the -L search paths
2147 dir_, libname = os.path.split(libname)
2148 linkdirs.add(dir_)
2149 if not bundle and static:
2150 modifiers.append('-bundle')
2151 if rustc.has_verbatim():
2152 modifiers.append('+verbatim')
2153 else:
2154 libname = rustc.lib_file_to_l_arg(libname)
2155 if libname is None:
2156 raise MesonException(f"rustc does not implement '-l{type_}:+verbatim'; cannot link to '{orig_libname}' due to nonstandard name")
2157
2158 if modifiers:
2159 type_ += ':' + ','.join(modifiers)
2160 args.append(f'-l{type_}={libname}')
2161
2162 for o in obj_list:
2163 args.append(f'-Clink-arg={o}')
2164 deps.append(o)
2165
2166 deps.extend([self.get_dependency_filename(t) for t in target.link_depends])
2167
2168 linkdirs: OrderedSet[str] = OrderedSet()
2169 external_deps = target.external_deps.copy()
2170 target_deps = target.get_dependencies()
2171 for d in target_deps:
2172 # rlibs only store -l flags, not -L; help out rustc and always
2173 # add the -L flag, in case it's needed to find non-bundled
2174 # dependencies of an rlib. At this point we don't have
2175 # information on whether this is a direct dependency (which
2176 # might use -Clink-arg= below) or an indirect one, so always
2177 # add to linkdirs.
2178 linkdirs.add(self.get_target_dir(d))
2179 deps.append(self.get_dependency_filename(d))
2180 if isinstance(d, build.StaticLibrary):
2181 external_deps.extend(d.external_deps)
2182 if d.uses_rust_abi():
2183 if d not in target.link_targets and d not in target.link_whole_targets:
2184 # Indirect Rust ABI dependency, we only need its path in linkdirs.
2185 continue
2186 assert isinstance(d, build.BuildTarget)
2187 # specify `extern CRATE_NAME=OUTPUT_FILE` for each Rust
2188 # dependency, so that collisions with libraries in rustc's
2189 # sysroot don't cause ambiguity
2190 d_name = self._get_rust_dependency_name(target, d)
2191 args += ['--extern', '{}={}'.format(d_name, self.get_target_filename(d))]
2192 project_deps.append(RustDep(d_name, self.rust_crates[d.name].order))
2193 continue
2194
2195 # Link a C ABI library
2196
2197 # Pass native libraries directly to the linker with "-C link-arg"
2198 # because rustc's "-l:+verbatim=" is not portable and we cannot rely
2199 # on linker to find the right library without using verbatim filename.
2200 # For example "-lfoo" won't find "foo.so" in the case name_prefix set
2201 # to "", or would always pick the shared library when both "libfoo.so"
2202 # and "libfoo.a" are available.
2203 # See https://doc.rust-lang.org/rustc/command-line-arguments.html#linking-modifiers-verbatim.
2204 #
2205 # However, rustc static linker (rlib and staticlib) requires using
2206 # "-l" argument and does not rely on platform specific dynamic linker.
2207 lib = self.get_target_filename_for_linking(d)
2208 link_whole = d in target.link_whole_targets
2209 if isinstance(target, build.StaticLibrary) or (isinstance(target, build.Executable) and rustc.get_crt_static()):
2210 static = isinstance(d, build.StaticLibrary)
2211 _link_library(lib, static, bundle=link_whole)
2212 elif link_whole:
2213 link_whole_args = rustc.linker.get_link_whole_for([lib])
2214 args += [f'-Clink-arg={a}' for a in link_whole_args]
2215 else:
2216 args.append(f'-Clink-arg={lib}')
2217
2218 for e in external_deps:
2219 prev: T.Optional[str] = None
2220 for prev, a in lookbehind(e.get_link_args()):
2221 if prev == '-framework':
2222 args.append(f'-lframework={a}')
2223 continue
2224 elif a.startswith('-L'):
2225 args.append(a)
2226 continue
2227 elif a.startswith('-F'):
2228 path = a[2:]
2229 args.append(f'-Lframework={path}')
2230 continue
2231 elif a == '-framework':
2232 # handled once the framework name is available
2233 continue
2234 elif is_library(a):
2235 if isinstance(target, build.StaticLibrary):
2236 static = a.endswith(('.a', '.lib'))
2237 _link_library(a, static)
2238 continue
2239
2240 dir_, _ = os.path.split(a)
2241 linkdirs.add(dir_)
2242
2243 args.append(f'-Clink-arg={a}')
2244
2245 for d in linkdirs:
2246 d = d or '.'
2247 args.append(f'-L{d}')
2248
2249 # Because of the way rustc links, this must come after any potential
2250 # library need to link with their stdlibs (C++ and Fortran, for example)
2251 args.extend(f'-Clink-arg={a}' for a in target.get_used_stdlib_args('rust'))
2252
2253 has_shared_deps = any(isinstance(dep, build.SharedLibrary) for dep in target_deps)
2254 has_rust_shared_deps = any(isinstance(dep, build.SharedLibrary) and dep.uses_rust()
2255 and dep.rust_crate_type == 'dylib'
2256 for dep in target_deps)
2257
2258 if target.rust_crate_type in {'dylib', 'proc-macro'}:
2259 # also add prefer-dynamic if any of the Rust libraries we link
2260 # against are dynamic or this is a dynamic library itself,
2261 # otherwise we'll end up with multiple implementations of libstd.
2262 has_rust_shared_deps = True
2263 elif self.get_target_option(target, 'rust_dynamic_std'):
2264 if target.rust_crate_type == 'staticlib':
2265 # staticlib crates always include a copy of the Rust libstd,
2266 # therefore it is not possible to also link it dynamically.
2267 # The options to avoid this (-Z staticlib-allow-rdylib-deps and
2268 # -Z staticlib-prefer-dynamic) are not yet stable; alternatively,
2269 # one could use "--emit obj" (implemented in the pull request at
2270 # https://github.com/mesonbuild/meson/pull/11213) or "--emit rlib"
2271 # (officially not recommended for linking with C programs).
2272 raise MesonException('rust_dynamic_std does not support staticlib crates yet')
2273 # want libstd as a shared dep
2274 has_rust_shared_deps = True
2275
2276 # Add link args specific to this BuildTarget type that must not be overridden by dependencies
2277 args += self.get_target_type_link_args_post_dependencies(target, rustc)
2278
2279 if has_rust_shared_deps:
2280 args += ['-C', 'prefer-dynamic']
2281 if has_shared_deps or has_rust_shared_deps:
2282 args += self.get_build_rpath_args(target, rustc)
2283
2284 return deps, project_deps, args
2285
2286 def generate_rust_target(self, target: build.BuildTarget, target_name: str, obj_list: T.List[str],
2287 fortran_order_deps: T.List[File]) -> None:
2288 orderdeps, main_rust_file = self.generate_rust_sources(target)
2289 if main_rust_file is None:
2290 raise RuntimeError('A Rust target has no Rust sources. This is weird. Also a bug. Please report')
2291
2292 rustc = T.cast('RustCompiler', target.compilers['rust'])
2293 args = rustc.compiler_args()
2294
2295 depfile = os.path.join(self.get_target_private_dir(target), target.name + '.d')
2296 args += self.get_rust_compiler_args(target, rustc, target.rust_crate_type, depfile)
2297
2298 deps, project_deps, deps_args = self.get_rust_compiler_deps_and_args(target, rustc, obj_list)
2299 args += deps_args
2300
2301 proc_macro_dylib_path = None
2302 if target.rust_crate_type == 'proc-macro':
2303 proc_macro_dylib_path = self.get_target_filename_abs(target)
2304
2305 self._add_rust_project_entry(target.name,
2306 os.path.abspath(os.path.join(self.environment.build_dir, main_rust_file)),
2307 args, target.rust_crate_type, target_name,
2308 bool(target.subproject),
2309 proc_macro_dylib_path,
2310 project_deps)
2311
2312 compiler_name = self.compiler_to_rule_name(rustc)
2313 element = NinjaBuildElement(self.all_outputs, target_name, compiler_name, main_rust_file)
2314 if orderdeps:
2315 element.add_orderdep(orderdeps)
2316 element.add_orderdep(self.order_deps_to_strings(target, fortran_order_deps))
2317 if deps:
2318 # dependencies need to cause a relink, they're not just for ordering
2319 element.add_dep(deps)
2320 element.add_item('ARGS', args)
2321 element.add_item('targetdep', depfile)
2322 self.add_build(element)
2323 self.create_target_source_introspection(target, rustc, args, [main_rust_file], [])
2324
2325 if target.doctests:
2326 assert target.doctests.target is not None
2327 rustdoc = rustc.get_rustdoc()
2328 args = rustdoc.get_exe_args() + \
2329 self.get_rust_compiler_args(target.doctests.target, rustdoc, target.rust_crate_type)
2330 o, _ = self.flatten_object_list(target.doctests.target)
2331 obj_list = unique_list(obj_list + o)
2332 # Rustc does not add files in the obj_list to Rust rlibs,
2333 # and is added by Meson to all of the dependencies, including here.
2334 _, _, deps_args = self.get_rust_compiler_deps_and_args(target.doctests.target, rustdoc, obj_list)
2335 args += deps_args
2336 target.doctests.cmd_args = args.to_native() + [main_rust_file] + target.doctests.cmd_args
2337
2338 @staticmethod
2339 def get_rule_suffix(for_machine: MachineChoice) -> str:
2340 return PerMachine('_FOR_BUILD', '')[for_machine]
2341
2342 @classmethod
2343 def get_compiler_rule_name(cls, lang: str, for_machine: MachineChoice, mode: str = 'COMPILER') -> str:
2344 return f'{lang}_{mode}{cls.get_rule_suffix(for_machine)}'
2345
2346 @classmethod
2347 def compiler_to_rule_name(cls, compiler: Compiler) -> str:
2348 return cls.get_compiler_rule_name(compiler.get_language(), compiler.for_machine, compiler.mode)
2349
2350 @classmethod
2351 def compiler_to_pch_rule_name(cls, compiler: Compiler) -> str:
2352 return cls.get_compiler_rule_name(compiler.get_language(), compiler.for_machine, 'PCH')
2353
2354 def swift_module_file_name(self, target: build.BuildTarget) -> str:
2355 return os.path.join(self.get_target_private_dir(target),
2356 target.swift_module_name + '.swiftmodule')
2357
2358 def determine_swift_dep_modules(self, target: build.BuildTarget) -> T.List[str]:
2359 result = []
2360 for l in target.link_targets:
2361 if self.is_swift_target(l):
2362 assert isinstance(l, build.BuildTarget) # for mypy
2363 result.append(self.swift_module_file_name(l))
2364 return result
2365
2366 def get_swift_link_deps(self, target: build.BuildTarget) -> T.List[str]:
2367 result = []
2368 for l in target.link_targets:
2369 result.append(self.get_target_filename(l))
2370 return result
2371
2372 def split_swift_generated_sources(self, target: build.BuildTarget) -> T.List[str]:
2373 all_srcs = self.get_target_generated_sources(target)
2374 srcs: T.List[str] = []
2375 for i in all_srcs:
2376 if i.endswith('.swift'):
2377 srcs.append(i)
2378 return srcs
2379
2380 def generate_swift_target(self, target: build.BuildTarget) -> None:
2381 module_name = target.swift_module_name
2382 swiftc = T.cast('SwiftCompiler', target.compilers['swift'])
2383 abssrc = []
2384 relsrc = []
2385 abs_headers = []
2386 header_imports = []
2387
2388 if not target.uses_swift_cpp_interop():
2389 cpp_targets = [t for t in target.link_targets if t.uses_swift_cpp_interop()]
2390 if cpp_targets != []:
2391 target_word = 'targets' if len(cpp_targets) > 1 else 'target'
2392 first = ', '.join(repr(t.name) for t in cpp_targets[:-1])
2393 and_word = ' and ' if len(cpp_targets) > 1 else ''
2394 last = repr(cpp_targets[-1].name)
2395 enable_word = 'enable' if len(cpp_targets) > 1 else 'enables'
2396 raise MesonException('Swift target {0} links against {1} {2}{3}{4} which {5} C++ interoperability. '
2397 'This requires {0} to also have it enabled. '
2398 'Add "swift_interoperability_mode: \'cpp\'" to the definition of {0}.'
2399 .format(repr(target.name), target_word, first, and_word, last, enable_word))
2400
2401 for i in target.get_sources():
2402 if swiftc.can_compile(i):
2403 rels = i.rel_to_builddir(self.build_to_src)
2404 abss = os.path.normpath(os.path.join(self.environment.get_build_dir(), rels))
2405 relsrc.append(rels)
2406 abssrc.append(abss)
2407 elif compilers.is_header(i):
2408 relh = i.rel_to_builddir(self.build_to_src)
2409 absh = os.path.normpath(os.path.join(self.environment.get_build_dir(), relh))
2410 abs_headers.append(absh)
2411 header_imports += swiftc.get_header_import_args(absh)
2412 else:
2413 raise InvalidArguments(f'Swift target {target.get_basename()} contains a non-swift source file.')
2414 os.makedirs(self.get_target_private_dir_abs(target), exist_ok=True)
2415 compile_args = self.generate_basic_compiler_args(target, swiftc)
2416 compile_args += swiftc.get_module_args(module_name)
2417 compile_args += swiftc.get_cxx_interoperability_args(target)
2418 compile_args += self.build.get_project_args(swiftc, target)
2419 compile_args += self.build.get_global_args(swiftc, target)
2420 if isinstance(target, (build.StaticLibrary, build.SharedLibrary)):
2421 # swiftc treats modules with a single source file, and the main.swift file in multi-source file modules
2422 # as top-level code. This is undesirable in library targets since it emits a main function. Add the
2423 # -parse-as-library option as necessary to prevent emitting the main function while keeping files explicitly
2424 # named main.swift treated as the entrypoint of the module in case this is desired.
2425 if len(abssrc) == 1 and os.path.basename(abssrc[0]) != 'main.swift':
2426 compile_args += swiftc.get_library_args()
2427 for i in reversed(target.get_include_dirs()):
2428 for path in i.abs_string_list(self.source_dir, self.build_dir):
2429 compile_args.extend(swiftc.get_include_args(path, False))
2430 compile_args += target.get_extra_args('swift')
2431 link_args = swiftc.get_output_args(os.path.join(self.environment.get_build_dir(), self.get_target_filename(target)))
2432 link_args += self.build.get_project_link_args(swiftc, target)
2433 link_args += self.build.get_global_link_args(swiftc, target)
2434 rundir = self.get_target_private_dir(target)
2435 out_module_name = self.swift_module_file_name(target)
2436 in_module_files = self.determine_swift_dep_modules(target)
2437 abs_module_dirs = self.determine_swift_dep_dirs(target)
2438 module_includes = []
2439 for x in abs_module_dirs:
2440 module_includes += swiftc.get_include_args(x, False)
2441 link_deps = self.get_swift_link_deps(target)
2442 abs_link_deps = [os.path.join(self.environment.get_build_dir(), x) for x in link_deps]
2443 for d in target.link_targets:
2444 reldir = self.get_target_dir(d)
2445 if reldir == '':
2446 reldir = '.'
2447 link_args += ['-L', os.path.normpath(os.path.join(self.environment.get_build_dir(), reldir))]
2448 rel_generated = self.split_swift_generated_sources(target)
2449 abs_generated = [os.path.join(self.environment.get_build_dir(), x) for x in rel_generated]
2450 # We need absolute paths because swiftc needs to be invoked in a subdir
2451 # and this is the easiest way about it.
2452 objects = [] # Relative to swift invocation dir
2453 rel_objects = [] # Relative to build.ninja
2454 for i in abssrc + abs_generated:
2455 base = os.path.basename(i)
2456 oname = os.path.splitext(base)[0] + '.o'
2457 objects.append(oname)
2458 rel_objects.append(os.path.join(self.get_target_private_dir(target), oname))
2459
2460 rulename = self.compiler_to_rule_name(swiftc)
2461
2462 # Swiftc does not seem to be able to emit objects and module files in one go.
2463 elem = NinjaBuildElement(self.all_outputs, rel_objects, rulename, abssrc)
2464 elem.add_dep(in_module_files + rel_generated)
2465 elem.add_dep(abs_headers)
2466 elem.add_item('ARGS', swiftc.get_compile_only_args() + compile_args + header_imports + abs_generated + module_includes)
2467 elem.add_item('RUNDIR', rundir)
2468 self.add_build(elem)
2469
2470 # -g makes swiftc create a .o file with potentially the same name as one of the compile target generated ones.
2471 mod_gen_args = [el for el in compile_args if el != '-g']
2472
2473 elem = NinjaBuildElement(self.all_outputs, out_module_name, rulename, abssrc)
2474 elem.add_dep(in_module_files + rel_generated)
2475 elem.add_item('ARGS', swiftc.get_mod_gen_args() + mod_gen_args + abs_generated + module_includes)
2476 elem.add_item('RUNDIR', rundir)
2477 self.add_build(elem)
2478 if isinstance(target, build.StaticLibrary):
2479 elem = self.generate_link(target, self.get_target_filename(target),
2480 rel_objects, self.build.static_linker[target.for_machine])
2481 self.add_build(elem)
2482 elif isinstance(target, build.Executable):
2483 elem = NinjaBuildElement(self.all_outputs, self.get_target_filename(target), rulename, [])
2484 elem.add_dep(rel_objects)
2485 elem.add_dep(link_deps)
2486 elem.add_item('ARGS', link_args + swiftc.get_std_exe_link_args() + objects + abs_link_deps)
2487 elem.add_item('RUNDIR', rundir)
2488 self.add_build(elem)
2489 else:
2490 raise MesonException('Swift supports only executable and static library targets.')
2491 # Introspection information
2492 self.create_target_source_introspection(target, swiftc, compile_args + header_imports + module_includes, relsrc, rel_generated)
2493
2494 def _rsp_options(self, tool: T.Union['Compiler', 'StaticLinker']) -> NinjaRuleArgs:
2495 """Helper method to get rsp options.
2496
2497 rsp_file_syntax() is only guaranteed to be implemented if
2498 can_linker_accept_rsp() returns True.
2499 """
2500 options: NinjaRuleArgs = {'rspable': tool.can_linker_accept_rsp()}
2501 if options['rspable']:
2502 options['rspfile_quote_style'] = tool.rsp_file_syntax()
2503 return options
2504
2505 def generate_static_link_rules(self) -> None:
2506 num_pools = self.environment.coredata.optstore.get_value_for('backend_max_links')
2507 assert isinstance(num_pools, int)
2508 if 'java' in self.environment.coredata.compilers.host:
2509 self.generate_java_link()
2510 for for_machine in MachineChoice:
2511 static_linker = self.build.static_linker[for_machine]
2512 if static_linker is None:
2513 continue
2514 rule = 'STATIC_LINKER{}'.format(self.get_rule_suffix(for_machine))
2515 cmdlist: CommandArgs = []
2516 args = ['$in']
2517 # FIXME: Must normalize file names with pathlib.Path before writing
2518 # them out to fix this properly on Windows. See:
2519 # https://github.com/mesonbuild/meson/issues/1517
2520 # https://github.com/mesonbuild/meson/issues/1526
2521 if isinstance(static_linker, ArLikeLinker) and not mesonlib.is_windows():
2522 # `ar` has no options to overwrite archives. It always appends,
2523 # which is never what we want. Delete an existing library first if
2524 # it exists. https://github.com/mesonbuild/meson/issues/1355
2525 cmdlist = execute_wrapper + [c.format('$out') for c in rmfile_prefix]
2526 cmdlist += static_linker.get_exelist()
2527 cmdlist += ['$LINK_ARGS']
2528 cmdlist += NinjaCommandArg.list(static_linker.get_output_args('$out'), Quoting.none)
2529 # The default ar on MacOS (at least through version 12), does not
2530 # add extern'd variables to the symbol table by default, and
2531 # requires that apple's ranlib be called with a special flag
2532 # instead after linking
2533 if static_linker.id == 'applear':
2534 # This is a bit of a hack, but we assume that that we won't need
2535 # an rspfile on MacOS, otherwise the arguments are passed to
2536 # ranlib, not to ar
2537 cmdlist.extend(args)
2538 args = []
2539 # Ensure that we use the user-specified ranlib if any, and
2540 # fallback to just picking up some ranlib otherwise
2541 ranlib = self.environment.lookup_binary_entry(for_machine, 'ranlib')
2542 if ranlib is None:
2543 ranlib = ['ranlib']
2544 cmdlist.extend(['&&'] + ranlib + ['-c', '$out'])
2545 description = 'Linking static target $out'
2546 if num_pools > 0:
2547 pool = 'pool = link_pool'
2548 else:
2549 pool = None
2550
2551 options = self._rsp_options(static_linker)
2552 self.add_rule(NinjaRule(rule, cmdlist, args, description, **options, extra=pool))
2553
2554 def generate_dynamic_link_rules(self) -> None:
2555 num_pools = self.environment.coredata.optstore.get_value_for('backend_max_links')
2556 assert isinstance(num_pools, int)
2557 for for_machine in MachineChoice:
2558 complist = self.environment.coredata.compilers[for_machine]
2559 for langname, compiler in complist.items():
2560 if langname in {'java', 'vala', 'rust', 'cs', 'cython'}:
2561 continue
2562 rule = '{}_LINKER{}'.format(langname, self.get_rule_suffix(for_machine))
2563 command = compiler.get_linker_exelist()
2564 args = ['$ARGS'] + NinjaCommandArg.list(compiler.get_linker_output_args('$out'), Quoting.none) + ['$in', '$LINK_ARGS']
2565 description = 'Linking target $out'
2566 if num_pools > 0:
2567 pool = 'pool = link_pool'
2568 else:
2569 pool = None
2570
2571 options = self._rsp_options(compiler)
2572 self.add_rule(NinjaRule(rule, command, args, description, **options, extra=pool))
2573 if self.environment.machines[for_machine].is_aix() and complist:
2574 rule = 'AIX_LINKER{}'.format(self.get_rule_suffix(for_machine))
2575 description = 'Archiving AIX shared library'
2576 cmdlist = compiler.get_command_to_archive_shlib()
2577 args = []
2578 options = {}
2579 self.add_rule(NinjaRule(rule, cmdlist, args, description, **options, extra=None))
2580 if self.environment.machines[for_machine].is_os2() and complist:
2581 rule = 'IMPORTLIB{}'.format(self.get_rule_suffix(for_machine))
2582 description = 'Generating import library $out'
2583 command = ['emximp']
2584 args = ['-o', '$out', '$in']
2585 options = {}
2586 self.add_rule(NinjaRule(rule, command, args, description, **options, extra=None))
2587
2588 args = self.environment.get_build_command() + \
2589 ['--internal',
2590 'symbolextractor',
2591 self.environment.get_build_dir(),
2592 '$in',
2593 '$IMPLIB',
2594 '$out']
2595 symrule = 'SHSYM'
2596 symcmd = args + ['$CROSS']
2597 syndesc = 'Generating symbol file $out'
2598 self.add_rule(NinjaRule(symrule, symcmd, [], syndesc, restat=True))
2599
2600 def generate_java_compile_rule(self, compiler: Compiler) -> None:
2601 rule = self.compiler_to_rule_name(compiler)
2602 command = compiler.get_exelist() + ['$ARGS', '$in']
2603 description = 'Compiling Java sources for $FOR_JAR'
2604 self.add_rule(NinjaRule(rule, command, [], description))
2605
2606 def generate_cs_compile_rule(self, compiler: 'CsCompiler') -> None:
2607 rule = self.compiler_to_rule_name(compiler)
2608 command = compiler.get_exelist()
2609 args = ['$ARGS', '$in']
2610 description = 'Compiling C Sharp target $out'
2611 self.add_rule(NinjaRule(rule, command, args, description,
2612 rspable=mesonlib.is_windows(),
2613 rspfile_quote_style=compiler.rsp_file_syntax()))
2614
2615 def generate_vala_compile_rules(self, compiler: Compiler) -> None:
2616 rule = self.compiler_to_rule_name(compiler)
2617 command = compiler.get_exelist()
2618 description = 'Compiling Vala source $in'
2619
2620 depargs = compiler.get_dependency_gen_args('$out', '$DEPFILE')
2621 depfile = '$DEPFILE' if depargs else None
2622 depstyle = 'gcc' if depargs else None
2623
2624 args = depargs + ['$ARGS', '$in']
2625
2626 self.add_rule(NinjaRule(rule, command + args, [], description,
2627 depfile=depfile,
2628 deps=depstyle,
2629 restat=True))
2630
2631 def generate_cython_compile_rules(self, compiler: 'Compiler') -> None:
2632 rule = self.compiler_to_rule_name(compiler)
2633 description = 'Compiling Cython source $in'
2634 command = compiler.get_exelist()
2635
2636 depargs = compiler.get_dependency_gen_args('$out', '$DEPFILE')
2637 depfile = '$out.dep' if depargs else None
2638
2639 args: CommandArgs = depargs + ['$ARGS', '$in']
2640 args += NinjaCommandArg.list(compiler.get_output_args('$out'), Quoting.none)
2641 self.add_rule(NinjaRule(rule, command + args, [],
2642 description,
2643 depfile=depfile,
2644 restat=True))
2645
2646 def generate_rust_compile_rules(self, compiler: RustCompiler) -> None:
2647 rule = self.compiler_to_rule_name(compiler)
2648 command = compiler.get_exelist() + ['$ARGS', '$in']
2649 description = 'Compiling Rust source $in'
2650 depfile = '$targetdep'
2651 depstyle = 'gcc'
2652 self.add_rule(NinjaRule(rule, command, [], description, deps=depstyle,
2653 depfile=depfile))
2654
2655 def generate_swift_compile_rules(self, compiler: SwiftCompiler) -> None:
2656 rule = self.compiler_to_rule_name(compiler)
2657 wd_args = compiler.get_working_directory_args('$RUNDIR')
2658
2659 if wd_args is not None:
2660 invoc = compiler.get_exelist() + wd_args
2661 else:
2662 full_exe = self.environment.get_build_command() + [
2663 '--internal',
2664 'dirchanger',
2665 '$RUNDIR',
2666 ]
2667 invoc = full_exe + compiler.get_exelist()
2668
2669 command = invoc + ['$ARGS', '$in']
2670 description = 'Compiling Swift source $in'
2671 self.add_rule(NinjaRule(rule, command, [], description, restat=True))
2672
2673 def use_dyndeps_for_fortran(self) -> bool:
2674 '''Use the new Ninja feature for scanning dependencies during build,
2675 rather than up front. Remove this and all old scanning code once Ninja
2676 minimum version is bumped to 1.10.'''
2677 return self.ninja_has_dyndeps
2678
2679 def get_fortran_order_deps(self, deps: T.List[build.BuildTarget]) -> T.List[File]:
2680 # We don't need this order dep if we're using dyndeps, as the
2681 # depscanner will handle this for us, which produces a better dependency
2682 # graph
2683 if self.use_dyndeps_for_fortran():
2684 return []
2685
2686 return [File(True, *os.path.split(self.get_target_filename(t))) for t in deps
2687 if t.uses_fortran()]
2688
2689 def generate_fortran_dep_hack(self, crstr: str) -> None:
2690 if self.use_dyndeps_for_fortran():
2691 return
2692 rule = f'FORTRAN_DEP_HACK{crstr}'
2693 if mesonlib.is_windows():
2694 cmd = ['cmd', '/C']
2695 else:
2696 cmd = ['true']
2697 self.add_rule_comment(NinjaComment('''Workaround for these issues:
2698 https://groups.google.com/forum/#!topic/ninja-build/j-2RfBIOd_8
2699 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47485'''))
2700 self.add_rule(NinjaRule(rule, cmd, [], 'Dep hack', restat=True))
2701
2702 def generate_llvm_ir_compile_rule(self, compiler: Compiler) -> None:
2703 if self.created_llvm_ir_rule[compiler.for_machine]:
2704 return
2705 rule = self.get_compiler_rule_name('llvm_ir', compiler.for_machine)
2706 command = compiler.get_exelist()
2707 args = ['$ARGS'] + NinjaCommandArg.list(compiler.get_output_args('$out'), Quoting.none) + compiler.get_compile_only_args() + ['$in']
2708 description = 'Compiling LLVM IR object $in'
2709
2710 options = self._rsp_options(compiler)
2711
2712 self.add_rule(NinjaRule(rule, command, args, description, **options))
2713 self.created_llvm_ir_rule[compiler.for_machine] = True
2714
2715 def generate_tasking_mil_compile_rules(self, compiler: Compiler) -> None:
2716 rule = self.get_compiler_rule_name('tasking_mil_compile', compiler.for_machine)
2717 depargs = NinjaCommandArg.list(compiler.get_dependency_gen_args('$out', '$DEPFILE'), Quoting.none)
2718 command = compiler.get_exelist()
2719 args = ['$ARGS'] + depargs + NinjaCommandArg.list(compiler.get_output_args('$out'), Quoting.none) + ['-cm', '$in']
2720 description = 'Compiling to C object $in'
2721 if compiler.get_depfile_format() == 'msvc':
2722 deps = 'msvc'
2723 depfile = None
2724 else:
2725 deps = 'gcc'
2726 depfile = '$DEPFILE'
2727
2728 options = self._rsp_options(compiler)
2729
2730 self.add_rule(NinjaRule(rule, command, args, description, **options, deps=deps, depfile=depfile))
2731
2732 def generate_tasking_mil_link_rules(self, compiler: Compiler) -> None:
2733 rule = self.get_compiler_rule_name('tasking_mil_link', compiler.for_machine)
2734 command = compiler.get_exelist()
2735 args = ['$ARGS', '--mil-link'] + NinjaCommandArg.list(compiler.get_output_args('$out'), Quoting.none) + ['-c', '$in']
2736 description = 'MIL linking object $out'
2737
2738 options = self._rsp_options(compiler)
2739
2740 self.add_rule(NinjaRule(rule, command, args, description, **options))
2741
2742 def generate_compile_rule_for(self, langname: str, compiler: Compiler) -> None:
2743 if langname == 'java':
2744 self.generate_java_compile_rule(compiler)
2745 return
2746 if langname == 'cs':
2747 if self.environment.machines.matches_build_machine(compiler.for_machine):
2748 self.generate_cs_compile_rule(T.cast('CsCompiler', compiler))
2749 return
2750 if langname == 'vala':
2751 self.generate_vala_compile_rules(compiler)
2752 return
2753 if langname == 'rust':
2754 self.generate_rust_compile_rules(T.cast('RustCompiler', compiler))
2755 return
2756 if langname == 'swift':
2757 if self.environment.machines.matches_build_machine(compiler.for_machine):
2758 self.generate_swift_compile_rules(T.cast('SwiftCompiler', compiler))
2759 return
2760 if langname == 'cython':
2761 self.generate_cython_compile_rules(compiler)
2762 return
2763 crstr = self.get_rule_suffix(compiler.for_machine)
2764 options = self._rsp_options(compiler)
2765 restat = False
2766 if langname == 'fortran':
2767 self.generate_fortran_dep_hack(crstr)
2768 # gfortran does not update the modification time of *.mod files, therefore restat is needed.
2769 # See also: https://github.com/ninja-build/ninja/pull/2275
2770 restat = True
2771 rule = self.compiler_to_rule_name(compiler)
2772 if langname == 'cuda':
2773 # for cuda, we manually escape target name ($out) as $CUDA_ESCAPED_TARGET because nvcc doesn't support `-MQ` flag
2774 depargs = NinjaCommandArg.list(compiler.get_dependency_gen_args('$CUDA_ESCAPED_TARGET', '$DEPFILE'), Quoting.none)
2775 else:
2776 depargs = NinjaCommandArg.list(compiler.get_dependency_gen_args('$out', '$DEPFILE'), Quoting.none)
2777 command = compiler.get_exelist()
2778 args = ['$ARGS'] + depargs + NinjaCommandArg.list(compiler.get_output_args('$out'), Quoting.none) + compiler.get_compile_only_args() + ['$in']
2779 description = f'Compiling {compiler.get_display_language()} object $out'
2780 if compiler.get_depfile_format() == 'msvc':
2781 deps = 'msvc'
2782 depfile = None
2783 else:
2784 deps = 'gcc'
2785 depfile = '$DEPFILE'
2786 self.add_rule(NinjaRule(rule, command, args, description, **options,
2787 deps=deps, depfile=depfile, restat=restat))
2788
2789 def generate_pch_rule_for(self, langname: str, compiler: Compiler) -> None:
2790 if langname not in {'c', 'cpp'}:
2791 return
2792 rule = self.compiler_to_pch_rule_name(compiler)
2793 depargs = compiler.get_dependency_gen_args('$out', '$DEPFILE')
2794
2795 if compiler.get_argument_syntax() == 'msvc':
2796 output = []
2797 else:
2798 output = NinjaCommandArg.list(compiler.get_output_args('$out'), Quoting.none)
2799
2800 if 'mwcc' in compiler.id:
2801 output[0].s = '-precompile'
2802 command = compiler.get_exelist() + ['$ARGS'] + depargs + output + ['$in'] # '-c' must be removed
2803 else:
2804 command = compiler.get_exelist() + ['$ARGS'] + depargs + output + compiler.get_compile_only_args() + ['$in']
2805 description = 'Precompiling header $in'
2806 if compiler.get_depfile_format() == 'msvc':
2807 deps = 'msvc'
2808 depfile = None
2809 else:
2810 deps = 'gcc'
2811 depfile = '$DEPFILE'
2812 self.add_rule(NinjaRule(rule, command, [], description, deps=deps,
2813 depfile=depfile))
2814
2815 def generate_scanner_rules(self) -> None:
2816 rulename = 'depscan'
2817 if self.ninja.has_rule(rulename):
2818 # Scanning command is the same for native and cross compilation.
2819 return
2820
2821 command = self.environment.get_build_command() + \
2822 ['--internal', 'depscan']
2823 args = ['$picklefile', '$out', '$in']
2824 description = 'Scanning target $name for modules'
2825 rule = NinjaRule(rulename, command, args, description)
2826 self.add_rule(rule)
2827
2828 rulename = 'depaccumulate'
2829 command = self.environment.get_build_command() + \
2830 ['--internal', 'depaccumulate']
2831 args = ['$out', '$in']
2832 description = 'Generating dynamic dependency information for target $name'
2833 rule = NinjaRule(rulename, command, args, description)
2834 self.add_rule(rule)
2835
2836 def generate_compile_rules(self) -> None:
2837 for for_machine in MachineChoice:
2838 clist = self.environment.coredata.compilers[for_machine]
2839 for langname, compiler in clist.items():
2840 if compiler.get_id() == 'clang':
2841 self.generate_llvm_ir_compile_rule(compiler)
2842 if compiler.get_id() == 'tasking':
2843 self.generate_tasking_mil_compile_rules(compiler)
2844 self.generate_compile_rule_for(langname, compiler)
2845 self.generate_pch_rule_for(langname, compiler)
2846 for mode in compiler.get_modes():
2847 self.generate_compile_rule_for(langname, mode)
2848
2849 def generate_generator_list_rules(self, target: build.BuildTarget) -> None:
2850 # CustomTargets have already written their rules and
2851 # CustomTargetIndexes don't actually get generated, so write rules for
2852 # GeneratedLists here
2853 for genlist in target.get_generated_sources():
2854 if isinstance(genlist, (build.CustomTarget, build.CustomTargetIndex)):
2855 continue
2856 self.generate_genlist_for_target(genlist, target)
2857
2858 def replace_paths(self, target: build.BuildTarget | build.CustomTarget, args: T.List[str], override_subdir: T.Optional[str] = None) -> T.List[str]:
2859 if override_subdir:
2860 source_target_dir = os.path.join(self.build_to_src, override_subdir)
2861 else:
2862 source_target_dir = self.get_target_source_dir(target)
2863 relout = self.get_target_private_dir(target)
2864 args = [x.replace("@SOURCE_DIR@", self.build_to_src).replace("@BUILD_DIR@", relout)
2865 for x in args]
2866 args = [x.replace("@CURRENT_SOURCE_DIR@", source_target_dir) for x in args]
2867 args = [x.replace("@SOURCE_ROOT@", self.build_to_src).replace("@BUILD_ROOT@", '.')
2868 for x in args]
2869 args = [x.replace('\\', '/') for x in args]
2870 return args
2871
2872 def generate_genlist_for_target(self, genlist: build.GeneratedList, target: build.BuildTarget | build.CustomTarget) -> None:
2873 for x in genlist.depends:
2874 if isinstance(x, build.GeneratedList):
2875 self.generate_genlist_for_target(x, target)
2876 generator = genlist.get_generator()
2877 subdir = genlist.subdir
2878 exe = generator.get_exe()
2879 infilelist = genlist.get_inputs()
2880 dependencies = self.get_target_depend_files(genlist)
2881 dependencies += self.get_paths_for_dep_outputs(target, generator.depends)
2882 dependencies += self.get_paths_for_dep_outputs(target, genlist.extra_depends)
2883 for curfile in infilelist:
2884 infilename = curfile.rel_to_builddir(self.build_to_src, self.get_target_private_dir(target))
2885 base_args = generator.get_arglist(infilename)
2886 outfiles = genlist.get_outputs_for(curfile)
2887 outfilespriv = [os.path.join(self.get_target_private_dir(target), of) for of in outfiles]
2888
2889 if len(generator.outputs) == 1:
2890 sole_output = outfilespriv[0]
2891 else:
2892 sole_output = f'{curfile}'
2893
2894 if generator.depfile is None:
2895 rulename = 'CUSTOM_COMMAND'
2896 args = base_args
2897 else:
2898 rulename = 'CUSTOM_COMMAND_DEP'
2899 depfilename = generator.get_dep_outname(infilename)
2900 if genlist.preserve_path_from:
2901 path_segment = genlist.get_preserved_path_segment(curfile)
2902 depfilename = os.path.join(path_segment, depfilename)
2903 depfile = os.path.join(self.get_target_private_dir(target), depfilename)
2904 args = [x.replace('@DEPFILE@', depfile) for x in base_args]
2905 args = [x.replace("@INPUT@", infilename).replace('@OUTPUT@', sole_output)
2906 for x in args]
2907 args = self.replace_outputs(args, self.get_target_private_dir(target), outfiles)
2908 args = self.replace_paths(target, args, override_subdir=subdir)
2909 cmdlist, reason = self.as_meson_exe_cmdline(exe,
2910 self.replace_extra_args(args, genlist),
2911 capture=outfilespriv[0] if generator.capture else None,
2912 env=genlist.env)
2913 abs_pdir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target))
2914 os.makedirs(abs_pdir, exist_ok=True)
2915
2916 elem = NinjaBuildElement(self.all_outputs, outfilespriv, rulename, infilename)
2917 elem.add_dep(dependencies)
2918 if generator.depfile is not None:
2919 elem.add_item('DEPFILE', depfile)
2920
2921 if len(generator.outputs) == 1:
2922 what = f'{sole_output!r}'
2923 else:
2924 # since there are multiple outputs, we log the source that caused the rebuild
2925 what = f'from {sole_output!r}'
2926 if reason:
2927 reason = f' (wrapped by meson {reason})'
2928 elem.add_item('DESC', f'Generating {what}{reason}')
2929
2930 elem.add_item('COMMAND', cmdlist)
2931 self.add_build(elem)
2932
2933 def scan_fortran_module_outputs(self, target: build.BuildTarget) -> None:
2934 """
2935 Find all module and submodule made available in a Fortran code file.
2936 """
2937 if self.use_dyndeps_for_fortran():
2938 return
2939 compiler = None
2940 # TODO other compilers
2941 for lang, c in self.environment.coredata.compilers.host.items():
2942 if lang == 'fortran':
2943 compiler = c
2944 break
2945 if compiler is None:
2946 self.fortran_deps[target.get_basename()] = {}
2947 return
2948
2949 modre = re.compile(FORTRAN_MODULE_PAT, re.IGNORECASE)
2950 submodre = re.compile(FORTRAN_SUBMOD_PAT, re.IGNORECASE)
2951 module_files: T.Dict[str, File] = {}
2952 submodule_files: T.Dict[str, File] = {}
2953 for s in target.get_sources():
2954 # FIXME, does not work for Fortran sources generated by
2955 # custom_target() and generator() as those are run after
2956 # the configuration (configure_file() is OK)
2957 if not compiler.can_compile(s):
2958 continue
2959 filename = s.absolute_path(self.environment.get_source_dir(),
2960 self.environment.get_build_dir())
2961 # Fortran keywords must be ASCII.
2962 with open(filename, encoding='ascii', errors='ignore') as f:
2963 for line in f:
2964 modmatch = modre.match(line)
2965 if modmatch is not None:
2966 modname = modmatch.group(1).lower()
2967 if modname in module_files:
2968 raise InvalidArguments(
2969 f'Namespace collision: module {modname} defined in '
2970 f'two files {module_files[modname]} and {s}.')
2971 module_files[modname] = s
2972 else:
2973 submodmatch = submodre.match(line)
2974 if submodmatch is not None:
2975 # '_' is arbitrarily used to distinguish submod from mod.
2976 parents = submodmatch.group(1).lower().split(':')
2977 submodname = parents[0] + '_' + submodmatch.group(2).lower()
2978
2979 if submodname in submodule_files:
2980 raise InvalidArguments(
2981 f'Namespace collision: submodule {submodname} defined in '
2982 f'two files {submodule_files[submodname]} and {s}.')
2983 submodule_files[submodname] = s
2984
2985 self.fortran_deps[target.get_basename()] = {**module_files, **submodule_files}
2986
2987 def get_fortran_deps(self, compiler: FortranCompiler, src: Path, target: build.BuildTarget) -> T.List[str]:
2988 """
2989 Find all module and submodule needed by a Fortran target
2990 """
2991 if self.use_dyndeps_for_fortran():
2992 return []
2993
2994 dirname = Path(self.get_target_private_dir(target))
2995 tdeps = self.fortran_deps[target.get_basename()]
2996 srcdir = Path(self.source_dir)
2997
2998 mod_files = _scan_fortran_file_deps(src, srcdir, dirname, tdeps, compiler)
2999 return mod_files
3000
3001 def get_no_stdlib_link_args(self, target: build.BuildTarget, linker: Compiler | StaticLinker) -> T.List[str]:
3002 if hasattr(linker, 'language') and linker.language in self.build.stdlibs[target.for_machine]:
3003 return linker.get_no_stdlib_link_args()
3004 return []
3005
3006 def get_compile_debugfile_args(self, compiler: Compiler, target: build.BuildTarget, objfile: str) -> T.List[str]:
3007 # The way MSVC uses PDB files is documented exactly nowhere so
3008 # the following is what we have been able to decipher via
3009 # reverse engineering.
3010 #
3011 # Each object file gets the path of its PDB file written
3012 # inside it. This can be either the final PDB (for, say,
3013 # foo.exe) or an object pdb (for foo.obj). If the former, then
3014 # each compilation step locks the pdb file for writing, which
3015 # is a bottleneck and object files from one target cannot be
3016 # used in a different target. The latter seems to be the
3017 # sensible one (and what Unix does) but there is a catch. If
3018 # you try to use precompiled headers MSVC will error out
3019 # because both source and pch pdbs go in the same file and
3020 # they must be the same.
3021 #
3022 # This means:
3023 #
3024 # - pch files must be compiled anew for every object file (negating
3025 # the entire point of having them in the first place)
3026 # - when using pch, output must go to the target pdb
3027 #
3028 # Since both of these are broken in some way, use the one that
3029 # works for each target. This unfortunately means that you
3030 # can't combine pch and object extraction in a single target.
3031 #
3032 # PDB files also lead to filename collisions. A target foo.exe
3033 # has a corresponding foo.pdb. A shared library foo.dll _also_
3034 # has pdb file called foo.pdb. So will a static library
3035 # foo.lib, which clobbers both foo.pdb _and_ the dll file's
3036 # export library called foo.lib (by default, currently we name
3037 # them libfoo.a to avoid this issue). You can give the files
3038 # unique names such as foo_exe.pdb but VC also generates a
3039 # bunch of other files which take their names from the target
3040 # basename (i.e. "foo") and stomp on each other.
3041 #
3042 # CMake solves this problem by doing two things. First of all
3043 # static libraries do not generate pdb files at
3044 # all. Presumably you don't need them and VC is smart enough
3045 # to look up the original data when linking (speculation, not
3046 # tested). The second solution is that you can only have
3047 # target named "foo" as an exe, shared lib _or_ static
3048 # lib. This makes filename collisions not happen. The downside
3049 # is that you can't have an executable foo that uses a shared
3050 # library libfoo.so, which is a common idiom on Unix.
3051 #
3052 # If you feel that the above is completely wrong and all of
3053 # this is actually doable, please send patches.
3054
3055 if target.has_pch():
3056 tfilename = self.get_target_debug_filename_abs(target)
3057 if not tfilename:
3058 tfilename = self.get_target_filename_abs(target)
3059 return compiler.get_compile_debugfile_args(tfilename, pch=True)
3060 else:
3061 return compiler.get_compile_debugfile_args(objfile, pch=False)
3062
3063 def get_link_debugfile_name(self, linker: T.Union[Compiler, StaticLinker], target: build.BuildTarget) -> T.Optional[str]:
3064 filename = self.get_target_debug_filename(target)
3065 if filename:
3066 return linker.get_link_debugfile_name(filename)
3067 return None
3068
3069 def get_link_debugfile_args(self, linker: T.Union[Compiler, StaticLinker], target: build.BuildTarget) -> T.List[str]:
3070 filename = self.get_target_debug_filename(target)
3071 if filename:
3072 return linker.get_link_debugfile_args(filename)
3073 return []
3074
3075 def generate_llvm_ir_compile(self, target: build.BuildTarget, src: FileOrString) -> T.Tuple[str, str]:
3076 compiler = get_compiler_for_source(target.compilers.values(), src)
3077 commands = compiler.compiler_args()
3078 # Compiler args for compiling this target
3079 commands += compilers.get_base_compile_args(target, compiler, self.environment)
3080 if isinstance(src, File):
3081 if src.is_built:
3082 src_filename = os.path.join(src.subdir, src.fname)
3083 else:
3084 src_filename = src.fname
3085 elif os.path.isabs(src):
3086 src_filename = os.path.basename(src)
3087 else:
3088 src_filename = src
3089 obj_basename = self.canonicalize_filename(src_filename)
3090 rel_obj = os.path.join(self.get_target_private_dir(target), obj_basename)
3091 rel_obj += '.' + self.environment.machines[target.for_machine].get_object_suffix()
3092 commands += self.get_compile_debugfile_args(compiler, target, rel_obj)
3093 if isinstance(src, File):
3094 if src.is_built:
3095 rel_src = src.fname
3096 else:
3097 rel_src = src.rel_to_builddir(self.build_to_src)
3098 else:
3099 raise InvalidArguments(f'Invalid source type: {src!r}')
3100 # Write the Ninja build command
3101 compiler_name = self.get_compiler_rule_name('llvm_ir', compiler.for_machine)
3102 element = NinjaBuildElement(self.all_outputs, rel_obj, compiler_name, rel_src)
3103 element.add_item('ARGS', commands)
3104 self.add_build(element)
3105 return (rel_obj, rel_src)
3106
3107 @lru_cache(maxsize=None)
3108 def generate_inc_dir(self, compiler: 'Compiler', d: str, basedir: str, is_system: bool
3109 ) -> T.Tuple[ImmutableListProtocol[str], ImmutableListProtocol[str]]:
3110 expdir = os.path.normpath(os.path.join(basedir, d))
3111 srctreedir = os.path.normpath(os.path.join(self.build_to_src, expdir))
3112 sargs = compiler.get_include_args(srctreedir, is_system)
3113 # There may be include dirs where a build directory has not been
3114 # created for some source dir. For example if someone does this:
3115 #
3116 # inc = include_directories('foo/bar/baz')
3117 #
3118 # But never subdir()s into the actual dir.
3119 if os.path.isdir(os.path.join(self.environment.get_build_dir(), expdir)):
3120 bargs = compiler.get_include_args(expdir, is_system)
3121 else:
3122 bargs = []
3123 return (sargs, bargs)
3124
3125 def _generate_single_compile(self, target: build.BuildTarget, compiler: Compiler) -> CompilerArgs:
3126 commands = target.get_single_compile_base_args(compiler)
3127 commands += self._generate_single_compile_target_args(target, compiler)
3128 return commands
3129
3130 @lru_cache(maxsize=None)
3131 def _generate_single_compile_target_args(self, target: build.BuildTarget, compiler: Compiler) -> ImmutableListProtocol[str]:
3132 # Add compiler args and include paths from several sources; defaults,
3133 # build options, external dependencies, etc.
3134 commands = self.generate_basic_compiler_args(target, compiler)
3135 commands += compiler.get_show_dep_args()
3136 # Add custom target dirs as includes automatically, but before
3137 # target-specific include directories.
3138 if target.implicit_include_directories:
3139 commands += self.get_custom_target_dir_include_args(target, compiler)
3140 # Add include dirs from the `include_directories:` kwarg on the target
3141 # and from `include_directories:` of internal deps of the target.
3142 #
3143 # Target include dirs should override internal deps include dirs.
3144 # This is handled in BuildTarget.process_kwargs()
3145 #
3146 # Include dirs from internal deps should override include dirs from
3147 # external deps and must maintain the order in which they are specified.
3148 # Hence, we must reverse the list so that the order is preserved.
3149 for i in reversed(target.get_include_dirs()):
3150 basedir = i.curdir
3151 # Each directory must be added to CompilerArgs individually
3152 # via a separate ``commands +=`` call, in reversed order.
3153 #
3154 # CompilerArgs.__iadd__ prepends ``-I`` args (which are in
3155 # CLikeCompilerArgs.prepend_prefixes) but appends ``-isystem``
3156 # args (which are not). When adding one directory at a time
3157 # in reversed order, this produces the correct result for
3158 # both flag types:
3159 #
3160 # - For ``-I`` (prepended): each flag is inserted at the
3161 # front, so reversed iteration produces the original
3162 # order — first-listed directory appears first on the
3163 # command line and is searched first.
3164 #
3165 # - For ``-isystem`` (appended): each flag is added at the
3166 # back, so reversed iteration produces a reversed sequence
3167 # on the command line — *last*-listed directory appears
3168 # first and is searched first.
3169 #
3170 # Adding all directories in a single ``commands +=`` call
3171 # would break ``-isystem`` ordering: the whole list would be
3172 # appended at once in the original (unreversed) order, making
3173 # the *first*-listed directory appear first instead of last.
3174 for d in reversed(i.incdirs):
3175 sargs, bargs = self.generate_inc_dir(compiler, d, basedir, i.is_system)
3176 commands += sargs
3177 commands += bargs
3178 for d in i.extra_build_dirs:
3179 commands += compiler.get_include_args(d, i.is_system)
3180 # Add per-target compile args, f.ex, `c_args : ['-DFOO']`. We set these
3181 # near the end since these are supposed to override everything else.
3182 commands += self.escape_extra_args(target.get_extra_args(compiler.get_language()))
3183
3184 # D specific additional flags
3185 if compiler.language == 'd':
3186 commands += compiler.get_feature_args(target.d_features, self.build_to_src)
3187
3188 # Add source dir and build dir. Project-specific and target-specific
3189 # include paths must override per-target compile args, include paths
3190 # from external dependencies, internal dependencies, and from
3191 # per-target `include_directories:`
3192 #
3193 # We prefer headers in the build dir over the source dir since, for
3194 # instance, the user might have an srcdir == builddir Autotools build
3195 # in their source tree. Many projects that are moving to Meson have
3196 # both Meson and Autotools in parallel as part of the transition.
3197 if target.implicit_include_directories:
3198 commands += self.get_source_dir_include_args(target, compiler)
3199 if target.implicit_include_directories:
3200 commands += self.get_build_dir_include_args(target, compiler)
3201 # Finally add the private dir for the target to the include path. This
3202 # must override everything else and must be the final path added.
3203 commands += compiler.get_include_args(self.get_target_private_dir(target), False)
3204 return list(commands)
3205
3206 # Returns a dictionary, mapping from each compiler src type (e.g. 'c', 'cpp', etc.) to a list of compiler arg strings
3207 # used for that respective src type.
3208 # Currently used for the purpose of populating VisualStudio intellisense fields but possibly useful in other scenarios.
3209 def generate_common_compile_args_per_src_type(self, target: build.BuildTarget) -> T.Dict[Language, T.List[str]]:
3210 src_type_to_args = {}
3211
3212 use_pch = self.target_uses_pch(target)
3213
3214 for src_type_str in target.compilers:
3215 compiler = target.compilers[src_type_str]
3216 commands = target.get_single_compile_base_args(compiler)
3217
3218 # Include PCH header as first thing as it must be the first one or it will be
3219 # ignored by gcc https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100462
3220 if use_pch and 'mw' not in compiler.id:
3221 commands += self.get_pch_include_args(compiler, target)
3222
3223 commands += self._generate_single_compile_target_args(target, compiler)
3224
3225 # Metrowerks compilers require PCH include args to come after intraprocedural analysis args
3226 if use_pch and 'mw' in compiler.id:
3227 commands += self.get_pch_include_args(compiler, target)
3228
3229 commands = commands.compiler.compiler_args(commands)
3230
3231 src_type_to_args[src_type_str] = commands.to_native()
3232 return src_type_to_args
3233
3234 def order_deps_to_strings(self, target: build.BuildTarget, order_deps: T.List[File] | T.List[FileOrString]) -> T.List[str]:
3235 result: T.List[str] = []
3236 for d in order_deps:
3237 if isinstance(d, File):
3238 d = d.rel_to_builddir(self.build_to_src)
3239 elif not self.has_dir_part(d):
3240 d = os.path.join(self.get_target_private_dir(target), d)
3241 result.append(d)
3242 return result
3243
3244 def generate_single_compile(self, target: build.BuildTarget, src: FileOrString,
3245 is_generated: bool = False,
3246 header_deps: T.Optional[T.List[FileOrString]] = None,
3247 order_deps: T.Optional[T.List[File] | T.List[FileOrString]] = None,
3248 extra_args: T.Optional[T.List[str]] = None,
3249 unity_sources: list[File] | None = None,
3250 ) -> T.Tuple[str, str]:
3251 """
3252 Compiles C/C++, ObjC/ObjC++, Fortran, and D sources
3253 """
3254 header_deps = header_deps if header_deps is not None else []
3255 order_deps = order_deps if order_deps is not None else []
3256
3257 if isinstance(src, str) and src.endswith('.h'):
3258 raise AssertionError(f'BUG: sources should not contain headers {src!r}')
3259
3260 compiler = get_compiler_for_source(target.compilers.values(), src)
3261 commands = target.get_single_compile_base_args(compiler)
3262
3263 # Include PCH header as first thing as it must be the first one or it will be
3264 # ignored by gcc https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100462
3265 use_pch = self.target_uses_pch(target)
3266 if use_pch and 'mw' not in compiler.id:
3267 commands += self.get_pch_include_args(compiler, target)
3268
3269 commands += self._generate_single_compile_target_args(target, compiler)
3270
3271 # Metrowerks compilers require PCH include args to come after intraprocedural analysis args
3272 if use_pch and 'mw' in compiler.id:
3273 commands += self.get_pch_include_args(compiler, target)
3274
3275 commands = commands.compiler.compiler_args(commands)
3276
3277 # Create introspection information
3278 if is_generated is False:
3279 self.create_target_source_introspection(target, compiler, commands, [src], [], unity_sources)
3280 else:
3281 self.create_target_source_introspection(target, compiler, commands, [], [src], unity_sources)
3282
3283 build_dir = self.environment.get_build_dir()
3284 if isinstance(src, File):
3285 if src.is_built and path_has_root(src.fname):
3286 raise MesonBugException('absolute file name for built file ' + src.relative_name())
3287 rel_src = src.rel_to_builddir(self.build_to_src)
3288 elif is_generated:
3289 raise AssertionError(f'BUG: broken generated source file handling for {src!r}')
3290 else:
3291 raise InvalidArguments(f'Invalid source type: {src!r}')
3292 obj_basename = self.object_filename_from_source(target, compiler, src)
3293 rel_obj = os.path.join(self.get_target_private_dir(target), obj_basename)
3294 dep_file = compiler.depfile_for_object(rel_obj)
3295
3296 # Add MSVC debug file generation compile flags: /Fd /FS
3297 commands += self.get_compile_debugfile_args(compiler, target, rel_obj)
3298
3299 # PCH handling. We only support PCH for C and C++
3300 if compiler.language in {'c', 'cpp'} and target.has_pch() and self.target_uses_pch(target):
3301 pchlist = target.pch[compiler.language]
3302 else:
3303 pchlist = None
3304 pch_dep: T.List[str]
3305 if not pchlist:
3306 pch_dep = []
3307 elif compiler.id == 'intel':
3308 pch_dep = []
3309 else:
3310 arr = []
3311 i = os.path.join(self.get_target_private_dir(target), compiler.get_pch_name(pchlist[0]))
3312 arr.append(i)
3313 pch_dep = arr
3314 # If TASKING compiler family is used and MIL linking is enabled for the target,
3315 # then compilation rule name is a special one to output MIL files
3316 # instead of object files for .c files
3317 if compiler.get_id() == 'tasking':
3318 target_lto = self.get_target_option(target, OptionKey('b_lto', machine=target.for_machine, subproject=target.subproject))
3319 if ((isinstance(target, build.StaticLibrary) and target.prelink) or target_lto) and src.rsplit('.', 1)[1] in compilers.lang_suffixes['c']:
3320 compiler_name = self.get_compiler_rule_name('tasking_mil_compile', compiler.for_machine)
3321 else:
3322 compiler_name = self.compiler_to_rule_name(compiler)
3323 else:
3324 compiler_name = self.compiler_to_rule_name(compiler)
3325 extra_deps = self.get_target_depend_files(target).copy()
3326 if compiler.get_language() == 'fortran':
3327 # Can't read source file to scan for deps if it's generated later
3328 # at build-time. Skip scanning for deps, and just set the module
3329 # outdir argument instead.
3330 # https://github.com/mesonbuild/meson/issues/1348
3331 if not is_generated:
3332 abs_src = Path(build_dir) / rel_src
3333 extra_deps += self.get_fortran_deps(T.cast('FortranCompiler', compiler),
3334 abs_src, target)
3335 if not self.use_dyndeps_for_fortran():
3336 # Dependency hack. Remove once multiple outputs in Ninja is fixed:
3337 # https://groups.google.com/forum/#!topic/ninja-build/j-2RfBIOd_8
3338 for modname, srcfile in self.fortran_deps[target.get_basename()].items():
3339 modfile = os.path.join(self.get_target_private_dir(target),
3340 compiler.module_name_to_filename(modname))
3341
3342 if srcfile == src:
3343 crstr = self.get_rule_suffix(target.for_machine)
3344 depelem = NinjaBuildElement(self.all_outputs,
3345 modfile,
3346 'FORTRAN_DEP_HACK' + crstr,
3347 rel_obj)
3348 self.add_build(depelem)
3349 commands += compiler.get_module_outdir_args(self.get_target_private_dir(target))
3350
3351 # C++ import std is complicated enough to get its own method.
3352 istd_args, istd_dep = self.handle_cpp_import_std(target, compiler)
3353 commands.extend(istd_args)
3354 header_deps += istd_dep
3355 if extra_args is not None:
3356 commands.extend(extra_args)
3357
3358 element = NinjaBuildElement(self.all_outputs, rel_obj, compiler_name, rel_src)
3359 self.add_header_deps(target, element, header_deps)
3360 for d in extra_deps:
3361 element.add_dep(d)
3362 element.add_orderdep(self.order_deps_to_strings(target, order_deps))
3363 element.add_dep(pch_dep)
3364 if not self.use_dyndeps_for_fortran():
3365 for i in self.get_fortran_module_deps(target, compiler):
3366 element.add_dep(i)
3367 if dep_file:
3368 element.add_item('DEPFILE', dep_file)
3369 if compiler.get_language() == 'cuda':
3370 # for cuda, we manually escape target name ($out) as $CUDA_ESCAPED_TARGET because nvcc doesn't support `-MQ` flag
3371 def quote_make_target(targetName: str) -> str:
3372 # this escape implementation is taken from llvm
3373 result = ''
3374 for (i, c) in enumerate(targetName):
3375 if c in {' ', '\t'}:
3376 # Escape the preceding backslashes
3377 for j in range(i - 1, -1, -1):
3378 if targetName[j] == '\\':
3379 result += '\\'
3380 else:
3381 break
3382 # Escape the space/tab
3383 result += '\\'
3384 elif c == '$':
3385 result += '$'
3386 elif c == '#':
3387 result += '\\'
3388 result += c
3389 return result
3390 element.add_item('CUDA_ESCAPED_TARGET', quote_make_target(rel_obj))
3391 if self.ninja.should_use_rspfile(element) and compiler.rsp_file_syntax() == RSPFileSyntax.NASM:
3392 exe = compiler.get_exelist()
3393 # Add to commands the args created by generate_compile_rule_for().
3394 # commands remain separate from exelist because they must stay
3395 # a CompilerArgs.
3396 if dep_file:
3397 commands += compiler.get_dependency_gen_args(rel_obj, dep_file)
3398 commands += [*compiler.get_output_args(rel_obj), *compiler.get_compile_only_args(), rel_src]
3399
3400 element.rulename = 'CUSTOM_COMMAND'
3401 meson_exe_cmd, reason = self.as_meson_exe_cmdline(exe[0],
3402 exe[1:] + commands.to_native(),
3403 separator='\n',
3404 rsp_file_flag='-@',
3405 can_use_rsp_file=True,
3406 verbose=True)
3407 cmd_type = f' (wrapped by meson {reason})' if reason else ''
3408 element.add_item('COMMAND', meson_exe_cmd)
3409 element.add_item('description', f'Compiling {compiler.get_display_language()} object {rel_obj}{cmd_type}')
3410 else:
3411 element.add_item('ARGS', commands)
3412
3413 self.add_dependency_scanner_entries_to_element(target, compiler, element, src)
3414 self.add_build(element)
3415 assert isinstance(rel_obj, str)
3416 assert isinstance(rel_src, str)
3417 return (rel_obj, rel_src.replace('\\', '/'))
3418
3419 def target_uses_import_std(self, target: build.BuildTarget) -> bool:
3420 if 'cpp' not in target.compilers:
3421 return False
3422 try:
3423 if self.environment.coredata.get_option_for_target(target, 'cpp_importstd') == 'true':
3424 return True
3425 except KeyError:
3426 pass
3427 return False
3428
3429 def handle_cpp_import_std(self, target: build.BuildTarget, compiler: Compiler) -> T.Tuple[T.List[str], T.List[File]]:
3430 istd_args: T.List[str] = []
3431 istd_dep: T.List[File] = []
3432 if not self.target_uses_import_std(target):
3433 return istd_args, istd_dep
3434 mlog.warning('Import std support is experimental and might break compatibility in the future.')
3435 # At the time of writing, all three major compilers work
3436 # wildly differently. Keep this isolated here until things
3437 # consolidate.
3438 if compiler.id == 'gcc':
3439 if self.import_std is None:
3440 mod_file = 'gcm.cache/std.gcm'
3441 mod_obj_file = 'std.o'
3442 elem = NinjaBuildElement(self.all_outputs, [mod_file, mod_obj_file], 'CUSTOM_COMMAND', [])
3443 compile_args = compiler.get_option_compile_args(target, target.subproject)
3444 compile_args += compiler.get_option_std_args(target, target.subproject)
3445 compile_args += ['-c', '-fmodules', '-fsearch-include-path', 'bits/std.cc']
3446 elem.add_item('COMMAND', compiler.exelist + compile_args)
3447 self.add_build(elem)
3448 self.import_std = ImportStdInfo(elem, mod_file, [mod_obj_file])
3449 istd_args = ['-fmodules']
3450 istd_dep = [File(True, '', self.import_std.gen_module_file)]
3451 return istd_args, istd_dep
3452 elif compiler.id == 'msvc':
3453 if self.import_std is None:
3454 mod_file = 'std.ifc'
3455 mod_obj_file = 'std.obj'
3456 in_file = Path(os.environ['VCToolsInstallDir']) / 'modules/std.ixx'
3457 if not in_file.is_file():
3458 raise SystemExit('VS std import header could not be located.')
3459 in_file_str = str(in_file)
3460 elem = NinjaBuildElement(self.all_outputs, [mod_file, mod_obj_file], 'CUSTOM_COMMAND', [in_file_str])
3461 compile_args = compiler.get_option_compile_args(target, target.subproject)
3462 compile_args += compiler.get_option_std_args(target, target.subproject)
3463 compile_args += ['/nologo', '/c', '/O2', in_file_str]
3464 elem.add_item('COMMAND', compiler.exelist + compile_args)
3465 self.add_build(elem)
3466 self.import_std = ImportStdInfo(elem, mod_file, [mod_obj_file])
3467 istd_dep = [File(True, '', self.import_std.gen_module_file)]
3468 return istd_args, istd_dep
3469 else:
3470 raise MesonException(f'Import std not supported on compiler {compiler.id} yet.')
3471
3472 def add_dependency_scanner_entries_to_element(self, target: build.BuildTarget, compiler: Compiler, element: NinjaBuildElement, src: File) -> None:
3473 if not self.should_use_dyndeps_for_target(target):
3474 return
3475 if isinstance(target, build.CompileTarget):
3476 return
3477 extension = os.path.splitext(src.fname)[1][1:]
3478 if extension != 'C':
3479 extension = extension.lower()
3480 if not (extension in compilers.lang_suffixes['fortran'] or extension in compilers.lang_suffixes['cpp']):
3481 return
3482 dep_scan_file = self.get_dep_scan_file_for(target)[1]
3483 element.add_item('dyndep', dep_scan_file)
3484 element.add_orderdep(dep_scan_file)
3485
3486 def get_dep_scan_file_for(self, target: build.BuildTarget) -> T.Tuple[str, str]:
3487 priv = self.get_target_private_dir(target)
3488 return os.path.join(priv, 'depscan.json'), os.path.join(priv, 'depscan.dd')
3489
3490 def add_header_deps(self, target: build.BuildTarget, ninja_element: NinjaBuildElement, header_deps: T.List[FileOrString]) -> None:
3491 for d in header_deps:
3492 if isinstance(d, File):
3493 d = d.rel_to_builddir(self.build_to_src)
3494 elif not self.has_dir_part(d):
3495 d = os.path.join(self.get_target_private_dir(target), d)
3496 ninja_element.add_orderdep(d)
3497
3498 def has_dir_part(self, fname: FileOrString) -> bool:
3499 # FIXME FIXME: The usage of this is a terrible and unreliable hack
3500 if isinstance(fname, File):
3501 return fname.subdir != ''
3502 return has_path_sep(fname)
3503
3504 # Fortran is a bit weird (again). When you link against a library, just compiling a source file
3505 # requires the mod files that are output when single files are built. To do this right we would need to
3506 # scan all inputs and write out explicit deps for each file. That is too slow and too much effort so
3507 # instead just have a full dependency on the library. This ensures all required mod files are created.
3508 # The real deps are then detected via dep file generation from the compiler. This breaks on compilers that
3509 # produce incorrect dep files but such is life. A full dependency is
3510 # required to ensure that if a new module is added to an existing file that
3511 # we correctly rebuild
3512 def get_fortran_module_deps(self, target: build.BuildTarget, compiler: Compiler) -> T.List[str]:
3513 # If we have dyndeps then we don't need this, since the depscanner will
3514 # do all of things described above.
3515 if compiler.language != 'fortran' or self.use_dyndeps_for_fortran():
3516 return []
3517 return [
3518 os.path.join(self.get_target_dir(lt), lt.get_filename())
3519 for lt in itertools.chain(target.link_targets, target.link_whole_targets)
3520 ]
3521
3522 def generate_msvc_pch_command(self, target: build.BuildTarget, compiler: Compiler, pch: T.Tuple[str, T.Optional[str]]) -> T.Tuple[T.List[str], str, str, T.List[str], str]:
3523 from ..compilers.mixins.visualstudio import VisualStudioLikeCompiler
3524 assert isinstance(compiler, VisualStudioLikeCompiler) # for mypy
3525 header = pch[0]
3526 pchname = compiler.get_pch_name(header)
3527 dst = os.path.join(self.get_target_private_dir(target), pchname)
3528
3529 commands: T.List[str] = []
3530 commands += self.generate_basic_compiler_args(target, compiler)
3531
3532 if pch[1] is None:
3533 # Auto generate PCH.
3534 source = self.create_msvc_pch_implementation(target, compiler.get_language(), pch[0])
3535 pch_header_dir = os.path.dirname(os.path.join(self.build_to_src, target.get_subdir(), header))
3536 commands += compiler.get_include_args(pch_header_dir, False)
3537 else:
3538 source = os.path.join(self.build_to_src, target.get_subdir(), pch[1])
3539
3540 just_name = os.path.basename(header)
3541 (objname, pch_args) = compiler.gen_pch_args(just_name, source, dst)
3542 commands += pch_args
3543 commands += self._generate_single_compile(target, compiler)
3544 commands += self.get_compile_debugfile_args(compiler, target, objname)
3545 dep = dst + '.' + compiler.get_depfile_suffix()
3546
3547 link_objects = [objname] if compiler.should_link_pch_object() else []
3548
3549 return commands, dep, dst, link_objects, source
3550
3551 def generate_gcc_pch_command(self, target: build.BuildTarget, compiler: Compiler, pch: str) -> T.Tuple[CompilerArgs, str, str, T.List[str]]:
3552 commands = self._generate_single_compile(target, compiler)
3553 if pch.split('.')[-1] == 'h' and compiler.language == 'cpp':
3554 # Explicitly compile pch headers as C++. If Clang is invoked in C++ mode, it actually warns if
3555 # this option is not set, and for gcc it also makes sense to use it.
3556 commands += ['-x', 'c++-header']
3557 dst = os.path.join(self.get_target_private_dir(target),
3558 os.path.basename(pch) + '.' + compiler.get_pch_suffix())
3559 dep = dst + '.' + compiler.get_depfile_suffix()
3560 return commands, dep, dst, [] # Gcc does not create an object file during pch generation.
3561
3562 def generate_mwcc_pch_command(self, target: build.BuildTarget, compiler: Compiler, pch: str) -> T.Tuple[CompilerArgs, str, str, T.List[str]]:
3563 commands = self._generate_single_compile(target, compiler)
3564 dst = os.path.join(self.get_target_private_dir(target),
3565 os.path.basename(pch) + '.' + compiler.get_pch_suffix())
3566 dep = os.path.splitext(dst)[0] + '.' + compiler.get_depfile_suffix()
3567 return commands, dep, dst, [] # mwcc compilers do not create an object file during pch generation.
3568
3569 def generate_pch(self, target: build.BuildTarget, header_deps: T.Optional[T.List[FileOrString]] = None) -> T.List[str]:
3570 header_deps = header_deps if header_deps is not None else []
3571 pch_objects = []
3572 for lang in T.cast('T.Tuple[Language, ...]', ('c', 'cpp')):
3573 pch = target.pch[lang]
3574 if not pch:
3575 continue
3576 if lang not in target.compilers:
3577 continue
3578 compiler: Compiler = target.compilers[lang]
3579 if compiler.get_argument_syntax() == 'msvc':
3580 (commands, dep, dst, objs, src) = self.generate_msvc_pch_command(target, compiler, pch)
3581 extradep = os.path.join(self.build_to_src, target.get_subdir(), pch[0])
3582 elif compiler.id == 'intel':
3583 # Intel generates on target generation
3584 continue
3585 elif 'mwcc' in compiler.id:
3586 src = os.path.join(self.build_to_src, target.get_subdir(), pch[0])
3587 (commands, dep, dst, objs) = self.generate_mwcc_pch_command(target, compiler, pch[0])
3588 extradep = None
3589 else:
3590 src = os.path.join(self.build_to_src, target.get_subdir(), pch[0])
3591 (commands, dep, dst, objs) = self.generate_gcc_pch_command(target, compiler, pch[0])
3592 extradep = None
3593 pch_objects += objs
3594 rulename = self.compiler_to_pch_rule_name(compiler)
3595 elem = NinjaBuildElement(self.all_outputs, objs + [dst], rulename, src)
3596 if extradep is not None:
3597 elem.add_dep(extradep)
3598 self.add_header_deps(target, elem, header_deps)
3599 elem.add_item('ARGS', commands)
3600 elem.add_item('DEPFILE', dep)
3601 self.add_build(elem)
3602 self.all_pch[compiler.id].update(objs + [dst])
3603 return pch_objects
3604
3605 def get_target_shsym_filename(self, target: build.BuildTarget) -> str:
3606 # Always name the .symbols file after the primary build output because it always exists
3607 targetdir = self.get_target_private_dir(target)
3608 return os.path.join(targetdir, target.get_filename() + '.symbols')
3609
3610 def generate_shsym(self, target: build.BuildTarget) -> None:
3611 # On OS/2, an import library is generated after linking a DLL, so
3612 # if a DLL is used as a target, import library is not generated.
3613 if self.environment.machines[target.for_machine].is_os2():
3614 target_file = self.get_target_filename_for_linking(target)
3615 else:
3616 target_file = self.get_target_filename(target)
3617 if isinstance(target, build.SharedLibrary) and target.aix_so_archive:
3618 if self.environment.machines[target.for_machine].is_aix():
3619 linker, stdlib_args = target.get_clink_dynamic_linker_and_stdlibs()
3620 target.get_outputs()[0] = linker.get_archive_name(target.get_outputs()[0])
3621 target_file = target.get_outputs()[0]
3622 target_file = os.path.join(self.get_target_dir(target), target_file)
3623 symname = self.get_target_shsym_filename(target)
3624 elem = NinjaBuildElement(self.all_outputs, symname, 'SHSYM', target_file)
3625 # The library we will actually link to, which is an import library on Windows (not the DLL)
3626 elem.add_item('IMPLIB', self.get_target_filename_for_linking(target))
3627 if self.environment.is_cross_build():
3628 elem.add_item('CROSS', '--cross-host=' + self.environment.machines[target.for_machine].system)
3629 self.add_build(elem)
3630
3631 def get_import_filename(self, target: build.Executable | build.SharedLibrary) -> str:
3632 return os.path.join(self.get_target_dir(target), target.import_filename)
3633
3634 def get_target_type_link_args(self, target: build.BuildTarget, linker: T.Union[StaticLinker, Compiler]) -> T.List[str]:
3635 if isinstance(target, build.StaticLibrary):
3636 produce_thin_archive = self.allow_thin_archives[target.for_machine] and not target.should_install()
3637 return linker.get_std_link_args(self.environment, produce_thin_archive)
3638
3639 assert isinstance(linker, Compiler)
3640 commands: T.List[str] = []
3641 if isinstance(target, build.Executable):
3642 # Currently only used with the Swift compiler to add '-emit-executable'
3643 commands += linker.get_std_exe_link_args()
3644 # If export_dynamic, add the appropriate linker arguments
3645 if target.export_dynamic:
3646 commands += linker.gen_export_dynamic_link_args()
3647 # If implib, and that's significant on this platform (i.e. Windows using either GCC or Visual Studio)
3648 if target.import_filename:
3649 commands += linker.gen_import_library_args(self.get_import_filename(target))
3650 if target.pie:
3651 commands += linker.get_pie_link_args()
3652 if target.vs_module_defs:
3653 commands += linker.gen_vs_module_defs_args(target.vs_module_defs.rel_to_builddir(self.build_to_src))
3654 elif isinstance(target, build.SharedLibrary):
3655 if isinstance(target, build.SharedModule):
3656 commands += linker.get_std_shared_module_link_args(target)
3657 else:
3658 commands += linker.get_std_shared_lib_link_args()
3659 # All shared libraries are PIC
3660 commands += linker.get_pic_args()
3661 # Add -Wl,-soname arguments on Linux, -install_name on OS X
3662 if not isinstance(target, build.SharedModule) or target.force_soname:
3663 commands += linker.get_soname_args(
3664 target.prefix, target.name, target.suffix,
3665 target.soversion, target.darwin_versions)
3666 if target.vs_module_defs:
3667 commands += linker.gen_vs_module_defs_args(target.vs_module_defs.rel_to_builddir(self.build_to_src))
3668 # This is only visited when building for Windows using either GCC or Visual Studio
3669 if target.import_filename:
3670 commands += linker.gen_import_library_args(self.get_import_filename(target))
3671 else:
3672 raise RuntimeError('Unknown build target type.')
3673 return commands
3674
3675 def get_target_type_link_args_post_dependencies(self, target: build.BuildTarget, linker: T.Union[Compiler, StaticLinker]) -> T.List[str]:
3676 commands: T.List[str] = []
3677 if isinstance(target, (build.Executable, build.SharedLibrary)):
3678 assert isinstance(linker, Compiler)
3679
3680 # If win_subsystem is significant on this platform, add the appropriate linker arguments.
3681 # Unfortunately this can't be done in get_target_type_link_args, because some misguided
3682 # libraries (such as SDL2) add -mwindows to their link flags.
3683 m = self.environment.machines[target.for_machine]
3684 if m.is_windows() or m.is_cygwin():
3685 commands += linker.get_win_subsystem_args(target.win_subsystem)
3686 return commands
3687
3688 def get_link_whole_args(self, linker: Compiler, target: build.BuildTarget) -> T.List[str]:
3689 use_custom = False
3690 if linker.id == 'msvc':
3691 # Expand our object lists manually if we are on pre-Visual Studio 2015 Update 2
3692 # (incidentally, the "linker" here actually refers to cl.exe)
3693 if mesonlib.version_compare(linker.version, '<19.00.23918'):
3694 use_custom = True
3695
3696 if use_custom:
3697 objects_from_static_libs: T.List[str] = []
3698 for dep in target.link_whole_targets:
3699 if not isinstance(dep, build.BuildTarget):
3700 raise MesonException(
3701 f'Cannot extract objects from custom target {dep.name!r} to '
3702 f'link_whole it into {target.name!r}: this is not supported '
3703 'with versions of MSVC older than Visual Studio 2015 Update 2.')
3704 l = dep.extract_all_objects(False)
3705 objects_from_static_libs += self.determine_ext_objs(l)
3706 objects_from_static_libs.extend(self.flatten_object_list(dep)[0])
3707
3708 return objects_from_static_libs
3709 else:
3710 target_args = self.build_target_link_arguments(linker, target.link_whole_targets)
3711 return linker.get_link_whole_for(target_args) if target_args else []
3712
3713 @lru_cache(maxsize=None)
3714 def guess_library_absolute_path(self, linker: Compiler, libname: str, search_dirs: T.Tuple[str, ...], patterns: T.Tuple[str, ...]) -> T.Optional[Path]:
3715 from ..compilers.c import CCompiler
3716 for d in search_dirs:
3717 for p in patterns:
3718 trial = CCompiler._get_trials_from_pattern(p, d, libname)
3719 if not trial:
3720 continue
3721 trial = CCompiler._get_file_from_list(self.environment, trial)
3722 if not trial:
3723 continue
3724 # Return the first result
3725 return trial
3726 return None
3727
3728 def guess_external_link_dependencies(self, linker: Compiler, target: build.BuildTarget, commands: CompilerArgs, internal: T.List[str]) -> T.List[str]:
3729 # Ideally the linker would generate dependency information that could be used.
3730 # But that has 2 problems:
3731 # * currently ld cannot create dependency information in a way that ninja can use:
3732 # https://sourceware.org/bugzilla/show_bug.cgi?id=22843
3733 # * Meson optimizes libraries from the same build using the symbol extractor.
3734 # Just letting ninja use ld generated dependencies would undo this optimization.
3735 search_dirs: OrderedSet[str] = OrderedSet()
3736 libs: OrderedSet[str] = OrderedSet()
3737 absolute_libs = []
3738
3739 build_dir = self.environment.get_build_dir()
3740 # the following loop sometimes consumes two items from command in one pass
3741 it = iter(linker.native_args_to_unix(list(commands)))
3742 for item in it:
3743 if item in internal and not item.startswith('-'):
3744 continue
3745
3746 if item.startswith('-L'):
3747 if len(item) > 2:
3748 path = item[2:]
3749 else:
3750 try:
3751 path = next(it)
3752 except StopIteration:
3753 mlog.warning("Generated linker command has -L argument without following path")
3754 break
3755 if not os.path.isabs(path):
3756 path = os.path.join(build_dir, path)
3757 search_dirs.add(path)
3758 elif item.startswith('-l'):
3759 if len(item) > 2:
3760 lib = item[2:]
3761 else:
3762 try:
3763 lib = next(it)
3764 except StopIteration:
3765 mlog.warning("Generated linker command has '-l' argument without following library name")
3766 break
3767 libs.add(lib)
3768 elif os.path.isabs(item) and compilers.is_library(item) and os.path.isfile(item):
3769 absolute_libs.append(item)
3770
3771 guessed_dependencies = []
3772 # TODO The get_library_naming requirement currently excludes link targets that use d or fortran as their main linker
3773 try:
3774 static_patterns = linker.get_library_naming(LibType.STATIC, strict=True)
3775 shared_patterns = linker.get_library_naming(LibType.SHARED, strict=True)
3776 search_dirs_tuple = tuple(search_dirs) + tuple(linker.get_library_dirs())
3777 for libname in libs:
3778 # be conservative and record most likely shared and static resolution, because we don't know exactly
3779 # which one the linker will prefer
3780 staticlibs = self.guess_library_absolute_path(linker, libname,
3781 search_dirs_tuple, static_patterns)
3782 sharedlibs = self.guess_library_absolute_path(linker, libname,
3783 search_dirs_tuple, shared_patterns)
3784 if staticlibs:
3785 guessed_dependencies.append(staticlibs.resolve().as_posix())
3786 if sharedlibs:
3787 guessed_dependencies.append(sharedlibs.resolve().as_posix())
3788 except (mesonlib.MesonException, AttributeError) as e:
3789 if 'get_library_naming' not in str(e):
3790 raise
3791
3792 return guessed_dependencies + absolute_libs
3793
3794 def generate_prelink(self, target: build.BuildTarget, obj_list: T.List[str]) -> T.List[str]:
3795 assert isinstance(target, build.StaticLibrary)
3796 prelink_name = os.path.join(self.get_target_private_dir(target), target.name + '-prelink.o')
3797 elem = NinjaBuildElement(self.all_outputs, [prelink_name], 'CUSTOM_COMMAND', obj_list)
3798
3799 prelinker = target.get_prelinker()
3800 cmd = prelinker.exelist[:]
3801 obj_list, args = prelinker.get_prelink_args(prelink_name, obj_list)
3802 cmd += args
3803 if prelinker.get_prelink_append_compile_args():
3804 compile_args = target.get_single_compile_base_args(prelinker)
3805 compile_args += self._generate_single_compile_target_args(target, prelinker)
3806 compile_args = compile_args.compiler.compiler_args(compile_args)
3807 cmd += compile_args.to_native()
3808
3809 cmd = self.replace_paths(target, cmd)
3810 elem.add_item('COMMAND', cmd)
3811 elem.add_item('description', f'Prelinking {prelink_name}')
3812 self.add_build(elem)
3813 return obj_list
3814
3815 def get_build_rpath_args(self, target: build.BuildTarget, linker: T.Union[Compiler, StaticLinker]) -> T.List[str]:
3816 if has_path_sep(target.name):
3817 # Target names really should not have slashes in them, but
3818 # unfortunately we did not check for that and some downstream projects
3819 # now have them. Once slashes are forbidden, remove this bit.
3820 target_slashname_workaround_dir = os.path.join(os.path.dirname(target.name),
3821 self.get_target_dir(target))
3822 else:
3823 target_slashname_workaround_dir = self.get_target_dir(target)
3824 (rpath_args, target.rpath_dirs_to_remove) = (
3825 linker.build_rpath_args(self.environment.get_build_dir(),
3826 target_slashname_workaround_dir,
3827 target))
3828 return rpath_args
3829
3830 def generate_link(self, target: build.BuildTarget, outname: str, obj_list: T.List[str],
3831 linker: T.Union[Compiler, StaticLinker],
3832 extra_objs: T.Optional[T.List[str]] = None,
3833 stdlib_args: T.Optional[T.List[str]] = None) -> NinjaBuildElement:
3834 extra_objs = extra_objs if extra_objs is not None else []
3835 stdlib_args = stdlib_args if stdlib_args is not None else []
3836 implicit_outs = []
3837 if isinstance(target, build.StaticLibrary):
3838 linker_base = 'STATIC'
3839 else:
3840 assert isinstance(linker, Compiler)
3841 linker_base = linker.get_language() # Fixme.
3842 if isinstance(target, build.SharedLibrary) and self.environment.machines[target.for_machine].is_os2():
3843 target_file = self.get_target_filename(target)
3844 import_name = self.get_import_filename(target)
3845 elem = NinjaBuildElement(self.all_outputs, import_name, 'IMPORTLIB', target_file)
3846 self.add_build(elem)
3847 crstr = self.get_rule_suffix(target.for_machine)
3848 linker_rule = linker_base + '_LINKER' + crstr
3849 # Create an empty commands list, and start adding link arguments from
3850 # various sources in the order in which they must override each other
3851 # starting from hard-coded defaults followed by build options and so on.
3852 #
3853 # Once all the linker options have been passed, we will start passing
3854 # libraries and library paths from internal and external sources.
3855 commands = linker.compiler_args()
3856 # First, the trivial ones that are impossible to override.
3857 #
3858 # Add linker args for linking this target derived from 'base' build
3859 # options passed on the command-line, in default_options, etc.
3860 # These have the lowest priority.
3861 if isinstance(target, build.StaticLibrary):
3862 assert isinstance(linker, StaticLinker)
3863 base_link_args = linker.get_base_link_args(target, linker, self.environment)
3864 else:
3865 assert isinstance(linker, Compiler)
3866 base_link_args = compilers.get_base_link_args(target,
3867 linker,
3868 self.environment)
3869 commands += self.transform_link_args(target, base_link_args)
3870 # Add -nostdlib if needed; can't be overridden
3871 commands += self.get_no_stdlib_link_args(target, linker)
3872 # Add things like /NOLOGO; usually can't be overridden
3873 commands += linker.get_linker_always_args()
3874 # Add buildtype linker args: optimization level, etc.
3875 optimization = self.get_target_option(target, 'optimization')
3876 assert isinstance(optimization, str)
3877 commands += linker.get_optimization_link_args(optimization)
3878 # Add /DEBUG and the pdb filename when using MSVC
3879 if self.get_target_option(target, 'debug'):
3880 commands += self.get_link_debugfile_args(linker, target)
3881 debugfile = self.get_link_debugfile_name(linker, target)
3882 if debugfile is not None:
3883 implicit_outs += [debugfile]
3884 # Add link args specific to this BuildTarget type, such as soname args,
3885 # PIC, import library generation, etc.
3886 commands += self.get_target_type_link_args(target, linker)
3887 if not isinstance(target, build.StaticLibrary):
3888 assert isinstance(linker, Compiler)
3889 # Archives that are copied wholesale in the result. Must be before any
3890 # other link targets so missing symbols from whole archives are found in those.
3891 commands += self.get_link_whole_args(linker, target)
3892 commands += linker.get_build_link_args(target, self.build)
3893
3894 # Now we will add libraries and library paths from various sources
3895
3896 # Set runtime-paths so we can run executables without needing to set
3897 # LD_LIBRARY_PATH, etc in the environment. Doesn't work on Windows.
3898 commands += self.get_build_rpath_args(target, linker)
3899
3900 # Add link args to link to all internal libraries (link_with:) and
3901 # internal dependencies needed by this target.
3902 dep_targets: T.List[str] = []
3903 dependencies: T.Iterable[build.BuildTargetTypes]
3904 if isinstance(target, build.StaticLibrary):
3905 # Link arguments of static libraries are not put in the command
3906 # line of the library. They are instead appended to the command
3907 # line where the static library is used.
3908 dependencies = []
3909 else:
3910 # Only non-static built targets need link args and link dependencies
3911 assert isinstance(linker, Compiler)
3912
3913 dependencies = target.get_dependencies()
3914 internal = self.build_target_link_arguments(linker, dependencies)
3915 commands += internal
3916
3917 # For 'automagic' deps: Boost and GTest. Also dependency('threads').
3918 # pkg-config puts the thread flags itself via `Cflags:`
3919 commands += linker.get_target_link_args(target)
3920 # External deps must be last because target link libraries may depend on them.
3921 for dep in target.get_external_deps():
3922 # Extend without reordering or de-dup to preserve `-L -l` sets
3923 # https://github.com/mesonbuild/meson/issues/1718
3924 commands.extend_preserving_lflags(linker.get_dependency_link_args(dep))
3925 for d in target.get_dependencies():
3926 if isinstance(d, build.StaticLibrary):
3927 for dep in d.get_external_deps():
3928 link_args = linker.get_dependency_link_args(dep)
3929 # Ensure that native static libraries use Unix-style naming if necessary.
3930 # Depending on the target/linker, rustc --print native-static-libs may
3931 # output MSVC-style names. Converting these to Unix-style is safe, as the
3932 # list contains only native static libraries.
3933 if dep.name == '_rust_native_static_libs' and linker.get_argument_syntax() != 'msvc':
3934 from ..linkers.linkers import VisualStudioLikeLinker
3935 link_args = VisualStudioLikeLinker.native_args_to_unix(link_args)
3936 commands.extend_preserving_lflags(link_args)
3937
3938 # Add link args specific to this BuildTarget type that must not be overridden by dependencies
3939 commands += self.get_target_type_link_args_post_dependencies(target, linker)
3940
3941 # Add link args for c_* or cpp_* build options. Currently this only
3942 # adds c_winlibs and cpp_winlibs when building for Windows. This needs
3943 # to be after all internal and external libraries so that unresolved
3944 # symbols from those can be found here. This is needed when the
3945 # *_winlibs that we want to link to are static mingw64 libraries.
3946 #
3947 # The static linker doesn't know what language it is building, so we
3948 # don't know what option. Fortunately, it doesn't care to see the
3949 # language-specific options either.
3950 #
3951 # We shouldn't check whether we are making a static library, because
3952 # in the LTO case we do use a real compiler here.
3953 commands += linker.get_option_link_args(target)
3954
3955 dep_targets.extend(self.guess_external_link_dependencies(linker, target, commands, internal))
3956
3957 obj_list += self.get_import_std_object(target)
3958
3959 # Add libraries generated by custom targets
3960 custom_target_libraries = self.get_custom_target_provided_libraries(target)
3961 commands += extra_objs
3962 commands += custom_target_libraries
3963 commands += stdlib_args # Standard library arguments go last, because they never depend on anything.
3964 dep_targets.extend([self.get_dependency_filename(t) for t in dependencies])
3965 dep_targets.extend([self.get_dependency_filename(t)
3966 for t in target.link_depends])
3967 elem = NinjaBuildElement(self.all_outputs, outname, linker_rule, obj_list, implicit_outs=implicit_outs)
3968 all_deps = [*dep_targets, *extra_objs, *custom_target_libraries]
3969 elem.add_dep(all_deps)
3970 if linker.get_id() == 'tasking':
3971 if any(x.endswith('.ma') for x in all_deps) and not self.get_target_option(target, OptionKey('b_lto', target.subproject, target.for_machine)):
3972 raise MesonException(f'Tried to link the target named \'{target.name}\' with a MIL archive without LTO enabled! This causes the compiler to ignore the archive.')
3973
3974 # Compiler args must be included in TI C28x linker commands.
3975 compile_args: T.List[str] = []
3976 if linker.get_id() in {'c2000', 'c6000', 'ti'}:
3977 for for_machine in MachineChoice:
3978 clist = self.environment.coredata.compilers[for_machine]
3979 for langname, compiler in clist.items():
3980 if langname in {'c', 'cpp'} and compiler.get_id() in {'c2000', 'c6000', 'ti'}:
3981 compile_args += self.generate_basic_compiler_args(target, compiler)
3982
3983 # Add early arguments before any object files or libraries
3984 if not isinstance(target, build.StaticLibrary):
3985 assert isinstance(linker, Compiler)
3986 compile_args += linker.get_target_link_early_args(target)
3987 if compile_args:
3988 elem.add_item('ARGS', compile_args)
3989 elem.add_item('LINK_ARGS', commands)
3990 self.create_target_linker_introspection(target, linker, commands)
3991 return elem
3992
3993 def get_import_std_object(self, target: build.BuildTarget) -> T.List[str]:
3994 if not self.target_uses_import_std(target):
3995 return []
3996 return self.import_std.gen_objects
3997
3998 def get_dependency_filename(self, t: T.Union[File, build.BuildTargetTypes]) -> str:
3999 if isinstance(t, build.SharedLibrary):
4000 if t.uses_rust() and t.rust_crate_type == 'proc-macro':
4001 return self.get_target_filename(t)
4002 else:
4003 return self.get_target_shsym_filename(t)
4004 elif isinstance(t, mesonlib.File):
4005 if t.is_built:
4006 return t.relative_name()
4007 else:
4008 return t.absolute_path(self.environment.get_source_dir(),
4009 self.environment.get_build_dir())
4010 return self.get_target_filename(t)
4011
4012 def generate_shlib_aliases(self, target: build.BuildTarget, outdir: str) -> None:
4013 for alias, to, tag in target.get_aliases():
4014 aliasfile = os.path.join(outdir, alias)
4015 abs_aliasfile = os.path.join(self.environment.get_build_dir(), outdir, alias)
4016 try:
4017 os.remove(abs_aliasfile)
4018 except Exception:
4019 pass
4020 try:
4021 os.symlink(to, abs_aliasfile)
4022 except NotImplementedError:
4023 mlog.debug("Library versioning disabled because symlinks are not supported.")
4024 except OSError:
4025 mlog.debug("Library versioning disabled because we do not have symlink creation privileges.")
4026 else:
4027 self.implicit_meson_outs.append(aliasfile)
4028
4029 def generate_custom_target_clean(self, trees: T.List[str]) -> str:
4030 e = self.create_phony_target('clean-ctlist', 'CUSTOM_COMMAND', 'PHONY')
4031 d = CleanTrees(self.environment.get_build_dir(), trees)
4032 d_file = os.path.join(self.environment.get_scratch_dir(), 'cleantrees.dat')
4033 e.add_item('COMMAND', self.environment.get_build_command() + ['--internal', 'cleantrees', d_file])
4034 e.add_item('description', 'Cleaning custom target directories')
4035 self.add_build(e)
4036 # Write out the data file passed to the script
4037 with open(d_file, 'wb') as ofile:
4038 pickle.dump(d, ofile)
4039 return 'clean-ctlist'
4040
4041 def generate_gcov_clean(self) -> None:
4042 gcno_elem = self.create_phony_target('clean-gcno', 'CUSTOM_COMMAND', 'PHONY')
4043 gcno_elem.add_item('COMMAND', mesonlib.get_meson_command() + ['--internal', 'delwithsuffix', '.', 'gcno'])
4044 gcno_elem.add_item('description', 'Deleting gcno files')
4045 self.add_build(gcno_elem)
4046
4047 gcda_elem = self.create_phony_target('clean-gcda', 'CUSTOM_COMMAND', 'PHONY')
4048 gcda_elem.add_item('COMMAND', mesonlib.get_meson_command() + ['--internal', 'delwithsuffix', '.', 'gcda'])
4049 gcda_elem.add_item('description', 'Deleting gcda files')
4050 self.add_build(gcda_elem)
4051
4052 def get_user_option_args(self) -> T.List[str]:
4053 cmds = []
4054 for k, v in self.environment.coredata.optstore.items():
4055 if self.environment.coredata.optstore.is_project_option(k):
4056 cmds.append('-D' + str(k) + '=' + (v.value if isinstance(v.value, str) else str(v.value).lower()))
4057 # The order of these arguments must be the same between runs of Meson
4058 # to ensure reproducible output. The order we pass them shouldn't
4059 # affect behavior in any other way.
4060 return sorted(cmds)
4061
4062 def generate_dist(self) -> None:
4063 elem = self.create_phony_target('dist', 'CUSTOM_COMMAND', 'PHONY')
4064 elem.add_item('DESC', 'Creating source packages')
4065 elem.add_item('COMMAND', self.environment.get_build_command() + ['dist'])
4066 elem.add_item('pool', 'console')
4067 self.add_build(elem)
4068
4069 def generate_clippy(self) -> None:
4070 if 'clippy' in self.all_outputs or not self.have_language('rust'):
4071 return
4072
4073 cmd = self.environment.get_build_command() + \
4074 ['--internal', 'clippy', self.environment.build_dir]
4075 elem = self.create_phony_target('clippy', 'CUSTOM_COMMAND', 'PHONY')
4076 elem.add_item('COMMAND', cmd)
4077 elem.add_item('pool', 'console')
4078 for crate in self.rust_crates.values():
4079 if crate.crate_type in {'rlib', 'dylib', 'proc-macro'}:
4080 elem.add_dep(crate.target_name)
4081 elem.add_dep(list(self.all_structured_sources))
4082 self.add_build(elem)
4083
4084 def generate_clippy_json_prereq(self) -> None:
4085 if 'clippy-json-prereq' in self.all_outputs or not self.have_language('rust'):
4086 return
4087
4088 elem = self.create_phony_target('clippy-json-prereq', 'CUSTOM_COMMAND', 'PHONY')
4089 for crate in self.rust_crates.values():
4090 if crate.crate_type in {'rlib', 'dylib', 'proc-macro'}:
4091 elem.add_dep(crate.target_name)
4092 elem.add_dep(list(self.all_structured_sources))
4093 self.add_build(elem)
4094
4095 def generate_clippy_json(self) -> None:
4096 if 'clippy-json' in self.all_outputs or not self.have_language('rust'):
4097 return
4098
4099 cmd = self.environment.get_build_command() + \
4100 ['--internal', 'clippy', self.environment.build_dir, '--error-format=json']
4101 elem = self.create_phony_target('clippy-json', 'CUSTOM_COMMAND', 'PHONY')
4102 elem.add_item('COMMAND', cmd)
4103 elem.add_item('pool', 'console')
4104 self.add_build(elem)
4105
4106 def generate_rustdoc(self) -> None:
4107 if 'rustdoc' in self.all_outputs or not self.have_language('rust'):
4108 return
4109
4110 cmd = self.environment.get_build_command() + \
4111 ['--internal', 'rustdoc', self.environment.build_dir]
4112 elem = self.create_phony_target('rustdoc', 'CUSTOM_COMMAND', 'PHONY')
4113 elem.add_item('COMMAND', cmd)
4114 elem.add_item('pool', 'console')
4115 for crate in self.rust_crates.values():
4116 if crate.crate_type in {'rlib', 'dylib', 'proc-macro'}:
4117 elem.add_dep(crate.target_name)
4118 elem.add_dep(list(self.all_structured_sources))
4119 self.add_build(elem)
4120
4121 def generate_scanbuild(self) -> None:
4122 if not tooldetect.detect_scanbuild():
4123 return
4124 if 'scan-build' in self.all_outputs:
4125 return
4126 cmd = self.environment.get_build_command() + \
4127 ['--internal', 'scanbuild', self.environment.source_dir, self.environment.build_dir, self.build.get_subproject_dir()] + \
4128 self.environment.get_build_command() + ['setup'] + self.get_user_option_args()
4129 elem = self.create_phony_target('scan-build', 'CUSTOM_COMMAND', 'PHONY')
4130 elem.add_item('COMMAND', cmd)
4131 elem.add_item('pool', 'console')
4132 self.add_build(elem)
4133
4134 def generate_clangtool(self, name: str, extra_arg: T.Optional[str] = None, need_pch: bool = False) -> None:
4135 target_name = 'clang-' + name
4136 extra_args = []
4137 if extra_arg:
4138 target_name += f'-{extra_arg}'
4139 extra_args.append(f'--{extra_arg}')
4140 colorout = self.environment.coredata.optstore.get_value_for('b_colorout') \
4141 if OptionKey('b_colorout') in self.environment.coredata.optstore else 'always'
4142 assert isinstance(colorout, str), 'for mypy'
4143 extra_args.extend(['--color', colorout])
4144 if not os.path.exists(os.path.join(self.environment.source_dir, '.clang-' + name)) and \
4145 not os.path.exists(os.path.join(self.environment.source_dir, '_clang-' + name)):
4146 return
4147 if target_name in self.all_outputs:
4148 return
4149 if need_pch and not set(self.all_pch.keys()) <= {'clang'}:
4150 return
4151
4152 cmd = self.environment.get_build_command() + \
4153 ['--internal', 'clang' + name, self.environment.source_dir, self.environment.build_dir] + \
4154 extra_args
4155 elem = self.create_phony_target(target_name, 'CUSTOM_COMMAND', 'PHONY')
4156 elem.add_item('COMMAND', cmd)
4157 elem.add_item('pool', 'console')
4158 if need_pch:
4159 elem.add_dep(list(self.all_pch['clang']))
4160 self.add_build(elem)
4161
4162 def generate_clangformat(self) -> None:
4163 if not tooldetect.detect_clangformat():
4164 return
4165 self.generate_clangtool('format')
4166 self.generate_clangtool('format', 'check')
4167
4168 def generate_clangtidy(self) -> None:
4169 if not tooldetect.detect_clangtidy():
4170 return
4171 self.generate_clangtool('tidy', need_pch=True)
4172 if not tooldetect.detect_clangapply():
4173 return
4174 self.generate_clangtool('tidy', 'fix', need_pch=True)
4175
4176 def generate_tags(self, tool: str, target_name: str) -> None:
4177 import shutil
4178 if not shutil.which(tool):
4179 return
4180 if target_name in self.all_outputs:
4181 return
4182 cmd = self.environment.get_build_command() + \
4183 ['--internal', 'tags', tool, self.environment.source_dir]
4184 elem = self.create_phony_target(target_name, 'CUSTOM_COMMAND', 'PHONY')
4185 elem.add_item('COMMAND', cmd)
4186 elem.add_item('pool', 'console')
4187 self.add_build(elem)
4188
4189 # For things like scan-build and other helper tools we might have.
4190 def generate_utils(self) -> None:
4191 self.generate_scanbuild()
4192 self.generate_clangformat()
4193 self.generate_clangtidy()
4194 self.generate_clippy()
4195 self.generate_clippy_json_prereq()
4196 self.generate_clippy_json()
4197 self.generate_rustdoc()
4198 self.generate_tags('etags', 'TAGS')
4199 self.generate_tags('ctags', 'ctags')
4200 self.generate_tags('cscope', 'cscope')
4201 cmd = self.environment.get_build_command() + ['--internal', 'uninstall']
4202 elem = self.create_phony_target('uninstall', 'CUSTOM_COMMAND', 'PHONY')
4203 elem.add_item('COMMAND', cmd)
4204 elem.add_item('pool', 'console')
4205 self.add_build(elem)
4206
4207 def generate_ending(self) -> None:
4208 for targ, deps in [
4209 ('all', self.get_build_by_default_targets().values()),
4210 ('meson-test-prereq', self.get_testlike_targets()),
4211 ('meson-benchmark-prereq', self.get_testlike_targets(True))]:
4212 targetlist = []
4213 for t in deps:
4214 # Add the first output of each target to the 'all' target so that
4215 # they are all built
4216 #Add archive file if shared library in AIX for build all.
4217 if isinstance(t, build.SharedLibrary) and t.aix_so_archive:
4218 if self.environment.machines[t.for_machine].is_aix():
4219 linker, stdlib_args = t.get_clink_dynamic_linker_and_stdlibs()
4220 t.get_outputs()[0] = linker.get_archive_name(t.get_outputs()[0])
4221 targetlist.append(os.path.join(self.get_target_dir(t), t.get_outputs()[0]))
4222
4223 # Add an import library if shared library in OS/2 for build all
4224 if isinstance(t, build.SharedLibrary):
4225 if self.environment.machines[t.for_machine].is_os2():
4226 targetlist.append(os.path.join(self.get_target_dir(t), t.import_filename))
4227
4228 elem = NinjaBuildElement(self.all_outputs, targ, 'phony', targetlist)
4229 self.add_build(elem)
4230
4231 elem = self.create_phony_target('clean', 'CUSTOM_COMMAND', 'PHONY')
4232 elem.add_item('COMMAND', self.ninja_command + ['-t', 'clean'])
4233 elem.add_item('description', 'Cleaning')
4234
4235 # If we have custom targets in this project, add all their outputs to
4236 # the list that is passed to the `cleantrees.py` script. The script
4237 # will manually delete all custom_target outputs that are directories
4238 # instead of files. This is needed because on platforms other than
4239 # Windows, Ninja only deletes directories while cleaning if they are
4240 # empty. https://github.com/mesonbuild/meson/issues/1220
4241 ctlist = []
4242 for t in self.build.get_targets().values():
4243 if isinstance(t, build.CustomTarget):
4244 # Create a list of all custom target outputs
4245 for o in t.get_outputs():
4246 ctlist.append(os.path.join(self.get_target_dir(t), o))
4247 # Also clean meson-dist directory created by `meson dist`
4248 ctlist.append('meson-dist')
4249 if ctlist:
4250 elem.add_dep(self.generate_custom_target_clean(ctlist))
4251
4252 if OptionKey('b_coverage') in self.environment.coredata.optstore and \
4253 self.environment.coredata.optstore.get_value_for('b_coverage'):
4254 self.generate_gcov_clean()
4255 elem.add_dep('clean-gcda')
4256 elem.add_dep('clean-gcno')
4257 self.add_build(elem)
4258
4259 deps = self.get_regen_filelist()
4260 elem = NinjaBuildElement(self.all_outputs, 'build.ninja', 'REGENERATE_BUILD', deps)
4261 elem.add_item('pool', 'console')
4262 self.add_build(elem)
4263
4264 # If these files used to be explicitly created, they need to appear on the build graph somehow,
4265 # otherwise cleandead deletes them. See https://github.com/ninja-build/ninja/issues/2299
4266 if self.implicit_meson_outs:
4267 elem = NinjaBuildElement(self.all_outputs, 'meson-implicit-outs', 'phony', self.implicit_meson_outs)
4268 self.add_build(elem)
4269
4270 elem = NinjaBuildElement(self.all_outputs, 'reconfigure', 'REGENERATE_BUILD', 'PHONY')
4271 elem.add_item('pool', 'console')
4272 self.add_build(elem)
4273
4274 elem = NinjaBuildElement(self.all_outputs, deps, 'phony', '')
4275 self.add_build(elem)
4276
4277 def get_introspection_data(self, target_id: str, target: build.Target) -> T.List[TargetIntrospectionData]:
4278 data = self.introspection_data.get(target_id)
4279 if not data:
4280 return super().get_introspection_data(target_id, target)
4281
4282 return list(data.values())
4283
4284
4285 def _scan_fortran_file_deps(src: Path, srcdir: Path, dirname: Path, tdeps: T.Dict[str, File], compiler: FortranCompiler) -> T.List[str]:
4286 """
4287 scan a Fortran file for dependencies. Needs to be distinct from target
4288 to allow for recursion induced by `include` statements.er
4289
4290 It makes a number of assumptions, including
4291
4292 * `use`, `module`, `submodule` name is not on a continuation line
4293
4294 Regex
4295 -----
4296
4297 * `incre` works for `#include "foo.f90"` and `include "foo.f90"`
4298 * `usere` works for legacy and Fortran 2003 `use` statements
4299 * `submodre` is for Fortran >= 2008 `submodule`
4300 """
4301
4302 incre = re.compile(FORTRAN_INCLUDE_PAT, re.IGNORECASE)
4303 usere = re.compile(FORTRAN_USE_PAT, re.IGNORECASE)
4304 submodre = re.compile(FORTRAN_SUBMOD_PAT, re.IGNORECASE)
4305
4306 mod_files = []
4307 src = Path(src)
4308 with src.open(encoding='ascii', errors='ignore') as f:
4309 for line in f:
4310 # included files
4311 incmatch = incre.match(line)
4312 if incmatch is not None:
4313 incfile = src.parent / incmatch.group(1)
4314 # NOTE: src.parent is most general, in particular for CMake subproject with Fortran file
4315 # having an `include 'foo.f'` statement.
4316 if incfile.suffix.lower()[1:] in compiler.file_suffixes:
4317 mod_files.extend(_scan_fortran_file_deps(incfile, srcdir, dirname, tdeps, compiler))
4318 # modules
4319 usematch = usere.match(line)
4320 if usematch is not None:
4321 usename = usematch.group(1).lower()
4322 if usename == 'intrinsic': # this keeps the regex simpler
4323 continue
4324 if usename not in tdeps:
4325 # The module is not provided by any source file. This
4326 # is due to:
4327 # a) missing file/typo/etc
4328 # b) using a module provided by the compiler, such as
4329 # OpenMP
4330 # There's no easy way to tell which is which (that I
4331 # know of) so just ignore this and go on. Ideally we
4332 # would print a warning message to the user but this is
4333 # a common occurrence, which would lead to lots of
4334 # distracting noise.
4335 continue
4336 srcfile = srcdir / tdeps[usename].fname
4337 if not srcfile.is_file():
4338 if srcfile.name != src.name: # generated source file
4339 pass
4340 else: # subproject
4341 continue
4342 elif srcfile.samefile(src): # self-reference
4343 continue
4344
4345 mod_name = compiler.module_name_to_filename(usename)
4346 mod_files.append(str(dirname / mod_name))
4347 else: # submodules
4348 submodmatch = submodre.match(line)
4349 if submodmatch is not None:
4350 parents = submodmatch.group(1).lower().split(':')
4351 assert len(parents) in {1, 2}, (
4352 'submodule ancestry must be specified as'
4353 f' ancestor:parent but Meson found {parents}')
4354
4355 ancestor_child = '_'.join(parents)
4356 if ancestor_child not in tdeps:
4357 raise MesonException("submodule {} relies on ancestor module {} that was not found.".format(submodmatch.group(2).lower(), ancestor_child.split('_', maxsplit=1)[0]))
4358 submodsrcfile = srcdir / tdeps[ancestor_child].fname
4359 if not submodsrcfile.is_file():
4360 if submodsrcfile.name != src.name: # generated source file
4361 pass
4362 else: # subproject
4363 continue
4364 elif submodsrcfile.samefile(src): # self-reference
4365 continue
4366 mod_name = compiler.module_name_to_filename(ancestor_child)
4367 mod_files.append(str(dirname / mod_name))
4368 return mod_files