| 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 '.\', or no path at all. |
| 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 |
# Add the private directories of the target itself, of all |
| 1119 |
# transitive dependencies, and of anywhere their mod files may |
| 1120 |
# have actually been compiled (see get_all_linked_targets). |
| 1121 |
fc = target.compilers['fortran'] |
| 1122 |
fortran_inc_args = mesonlib.listify([fc.get_include_args( |
| 1123 |
self.get_target_private_dir(t), is_system=False) |
| 1124 |
for t in self.get_all_linked_targets(target) |
| 1125 |
if t.uses_fortran()]) |
| 1126 |
|
| 1127 |
# Generate compilation targets for sources generated by transpilers. |
| 1128 |
# |
| 1129 |
# Do not try to unity-build the generated source files, as these |
| 1130 |
# often contain duplicate symbols and will fail to compile properly. |
| 1131 |
# |
| 1132 |
# Gather all generated source files and header before generating the |
| 1133 |
# compilation rules, to be able to add correct dependencies on the |
| 1134 |
# generated headers. |
| 1135 |
transpiled_source_files = [] |
| 1136 |
for src in transpiled_sources: |
| 1137 |
raw_src = File.from_built_relative(src) |
| 1138 |
# Generated targets are ordered deps because the must exist |
| 1139 |
# before the sources compiling them are used. After the first |
| 1140 |
# compile we get precise dependency info from dep files. |
| 1141 |
# This should work in all cases. If it does not, then just |
| 1142 |
# move them from orderdeps to proper deps. |
| 1143 |
if compilers.is_header(src): |
| 1144 |
header_deps.append(raw_src) |
| 1145 |
else: |
| 1146 |
transpiled_source_files.append(raw_src) |
| 1147 |
for src in transpiled_source_files: |
| 1148 |
o, s = self.generate_single_compile(target, src, True, [], header_deps) |
| 1149 |
obj_list.append(o) |
| 1150 |
|
| 1151 |
# Generate compile targets for all the preexisting sources for this target |
| 1152 |
for src in target_sources.values(): |
| 1153 |
if not compilers.is_separate_compile(src): |
| 1154 |
continue |
| 1155 |
if compilers.is_header(src) and not is_compile_target: |
| 1156 |
continue |
| 1157 |
if compilers.is_llvm_ir(src): |
| 1158 |
o, s = self.generate_llvm_ir_compile(target, src) |
| 1159 |
obj_list.append(o) |
| 1160 |
elif is_unity and self.get_target_source_can_unity(target, src): |
| 1161 |
unity_src.append(src) |
| 1162 |
else: |
| 1163 |
o, s = self.generate_single_compile(target, src, False, [], |
| 1164 |
[*header_deps, *d_generated_deps, *fortran_order_deps], |
| 1165 |
fortran_inc_args) |
| 1166 |
obj_list.append(o) |
| 1167 |
compiled_sources.append(s) |
| 1168 |
source2object[s] = o |
| 1169 |
|
| 1170 |
if is_unity: |
| 1171 |
for src in self.generate_unity_files(target, unity_src): |
| 1172 |
o, s = self.generate_single_compile(target, src, True, [*unity_deps, *header_deps, *d_generated_deps], |
| 1173 |
fortran_order_deps, fortran_inc_args, unity_src) |
| 1174 |
obj_list.append(o) |
| 1175 |
compiled_sources.append(s) |
| 1176 |
source2object[s] = o |
| 1177 |
if is_compile_target: |
| 1178 |
# Skip the link stage for this special type of target |
| 1179 |
return |
| 1180 |
|
| 1181 |
if not isinstance(target, build.StaticLibrary): |
| 1182 |
final_obj_list = obj_list |
| 1183 |
elif target.prelink: |
| 1184 |
final_obj_list = self.generate_prelink(target, obj_list) |
| 1185 |
else: |
| 1186 |
final_obj_list = obj_list |
| 1187 |
|
| 1188 |
self.generate_dependency_scan_target(target, compiled_sources, source2object, fortran_order_deps) |
| 1189 |
|
| 1190 |
if isinstance(target, build.SharedLibrary): |
| 1191 |
self.generate_shsym(target) |
| 1192 |
if target.uses_rust(): |
| 1193 |
self.generate_rust_target(target, outname, final_obj_list, fortran_order_deps) |
| 1194 |
return |
| 1195 |
|
| 1196 |
linker, stdlib_args = self.determine_linker_and_stdlib_args(target) |
| 1197 |
elem = self.generate_link(target, outname, final_obj_list, linker, pch_objects, stdlib_args=stdlib_args) |
| 1198 |
self.add_build(elem) |
| 1199 |
#In AIX, we archive shared libraries. If the instance is a shared library, we add a command to archive the shared library |
| 1200 |
#object and create the build element. |
| 1201 |
if isinstance(target, build.SharedLibrary) and self.environment.machines[target.for_machine].is_aix(): |
| 1202 |
if target.aix_so_archive: |
| 1203 |
elem = NinjaBuildElement(self.all_outputs, linker.get_archive_name(outname), 'AIX_LINKER', [outname]) |
| 1204 |
self.add_build(elem) |
| 1205 |
|
| 1206 |
def should_use_dyndeps_for_target(self, target: build.BuildTargetTypes) -> bool: |
| 1207 |
if not self.ninja_has_dyndeps: |
| 1208 |
return False |
| 1209 |
if not isinstance(target, build.BuildTarget): |
| 1210 |
return False |
| 1211 |
if 'fortran' in target.compilers: |
| 1212 |
return True |
| 1213 |
if 'cpp' not in target.compilers: |
| 1214 |
return False |
| 1215 |
for arg in target.compilers['cpp'].get_cpp_modules_args(): |
| 1216 |
if arg in target.extra_args['cpp']: |
| 1217 |
return True |
| 1218 |
# Currently only the preview version of Visual Studio is supported. |
| 1219 |
cpp = target.compilers['cpp'] |
| 1220 |
if cpp.get_id() != 'msvc': |
| 1221 |
return False |
| 1222 |
cppversion = self.get_target_option(target, OptionKey('cpp_std', |
| 1223 |
machine=target.for_machine, |
| 1224 |
subproject=target.subproject)) |
| 1225 |
if cppversion not in ('latest', 'c++latest', 'vc++latest'): |
| 1226 |
return False |
| 1227 |
if not mesonlib.current_vs_supports_modules(): |
| 1228 |
return False |
| 1229 |
if mesonlib.version_compare(cpp.version, '<19.28.28617'): |
| 1230 |
return False |
| 1231 |
return True |
| 1232 |
|
| 1233 |
def generate_dependency_scan_target(self, target: build.BuildTarget, |
| 1234 |
compiled_sources: T.List[str], |
| 1235 |
source2object: T.Dict[str, str], |
| 1236 |
object_deps: T.List[File]) -> None: |
| 1237 |
if not self.should_use_dyndeps_for_target(target): |
| 1238 |
return |
| 1239 |
self._uses_dyndeps = True |
| 1240 |
json_file, depscan_file = self.get_dep_scan_file_for(target) |
| 1241 |
pickle_base = target.name + '.dat' |
| 1242 |
pickle_file = os.path.join(self.get_target_private_dir(target), pickle_base).replace('\\', '/') |
| 1243 |
pickle_abs = os.path.join(self.get_target_private_dir_abs(target), pickle_base).replace('\\', '/') |
| 1244 |
rule_name = 'depscan' |
| 1245 |
scan_sources = list(self.select_sources_to_scan(compiled_sources)) |
| 1246 |
|
| 1247 |
scaninfo = TargetDependencyScannerInfo( |
| 1248 |
self.get_target_private_dir(target), source2object, scan_sources) |
| 1249 |
|
| 1250 |
write = True |
| 1251 |
if os.path.exists(pickle_abs): |
| 1252 |
with open(pickle_abs, 'rb') as p: |
| 1253 |
old = pickle.load(p) |
| 1254 |
write = old != scaninfo |
| 1255 |
|
| 1256 |
if write: |
| 1257 |
with open(pickle_abs, 'wb') as p: |
| 1258 |
pickle.dump(scaninfo, p) |
| 1259 |
|
| 1260 |
elem = NinjaBuildElement(self.all_outputs, json_file, rule_name, pickle_file) |
| 1261 |
# A full dependency is required on all scanned sources, if any of them |
| 1262 |
# are updated we need to rescan, as they may have changed the modules |
| 1263 |
# they use or export. |
| 1264 |
for s in scan_sources: |
| 1265 |
elem.deps.add(s[0]) |
| 1266 |
elem.add_orderdep(self.order_deps_to_strings(target, object_deps)) |
| 1267 |
elem.add_item('name', target.name) |
| 1268 |
self.add_build(elem) |
| 1269 |
|
| 1270 |
infiles: T.Set[str] = set() |
| 1271 |
for t in self.get_all_linked_targets(target): |
| 1272 |
if self.should_use_dyndeps_for_target(t): |
| 1273 |
assert isinstance(t, build.BuildTarget) |
| 1274 |
infiles.add(self.get_dep_scan_file_for(t)[0]) |
| 1275 |
|
| 1276 |
elem = NinjaBuildElement(self.all_outputs, depscan_file, 'depaccumulate', [json_file] + sorted(infiles)) |
| 1277 |
elem.add_item('name', target.name) |
| 1278 |
self.add_build(elem) |
| 1279 |
|
| 1280 |
def select_sources_to_scan(self, compiled_sources: T.List[str], |
| 1281 |
) -> T.Iterable[T.Tuple[str, Literal['cpp', 'fortran']]]: |
| 1282 |
# in practice pick up C++ and Fortran files. If some other language |
| 1283 |
# requires scanning (possibly Java to deal with inner class files) |
| 1284 |
# then add them here. |
| 1285 |
for source in compiled_sources: |
| 1286 |
if isinstance(source, mesonlib.File): |
| 1287 |
source = source.rel_to_builddir(self.build_to_src) |
| 1288 |
ext = os.path.splitext(source)[1][1:] |
| 1289 |
if ext.lower() in compilers.lang_suffixes['cpp'] or ext == 'C': |
| 1290 |
yield source, 'cpp' |
| 1291 |
elif ext.lower() in compilers.lang_suffixes['fortran']: |
| 1292 |
yield source, 'fortran' |
| 1293 |
|
| 1294 |
def process_target_dependencies(self, target: build.BuildTarget) -> None: |
| 1295 |
for t in target.get_dependencies(): |
| 1296 |
if t.get_id() not in self.processed_targets: |
| 1297 |
self.generate_target(t.get_target()) |
| 1298 |
|
| 1299 |
def custom_target_generator_inputs(self, target: build.CustomTarget) -> None: |
| 1300 |
for s in target.sources: |
| 1301 |
if isinstance(s, build.GeneratedList): |
| 1302 |
self.generate_genlist_for_target(s, target) |
| 1303 |
|
| 1304 |
def generate_custom_target(self, target: build.CustomTarget) -> None: |
| 1305 |
self.custom_target_generator_inputs(target) |
| 1306 |
(srcs, ofilenames, cmd) = self.eval_custom_target_command(target) |
| 1307 |
deps = self.get_paths_for_dep_outputs(target, target.get_dependencies()) |
| 1308 |
deps += self.get_target_depend_files(target) |
| 1309 |
deps += self.get_paths_for_dep_outputs(target, target.extra_depends) |
| 1310 |
if target.build_always_stale: |
| 1311 |
deps.append('PHONY') |
| 1312 |
if target.depfile_type == 'gcc': |
| 1313 |
rulename = 'CUSTOM_COMMAND_DEP' |
| 1314 |
elif target.depfile_type == 'msvc': |
| 1315 |
rulename = 'CUSTOM_COMMAND_MSVC_DEP' |
| 1316 |
else: |
| 1317 |
rulename = 'CUSTOM_COMMAND' |
| 1318 |
elem = NinjaBuildElement(self.all_outputs, ofilenames, rulename, srcs) |
| 1319 |
elem.add_dep(deps) |
| 1320 |
|
| 1321 |
cmd, reason = self.as_meson_exe_cmdline(target.command[0], cmd[1:], |
| 1322 |
extra_bdeps=target.get_transitive_build_target_deps(), |
| 1323 |
capture=ofilenames[0] if target.capture else None, |
| 1324 |
feed=srcs[0] if target.feed else None, |
| 1325 |
env=target.env, |
| 1326 |
can_use_rsp_file=target.rspable, |
| 1327 |
verbose=target.console) |
| 1328 |
if reason: |
| 1329 |
cmd_type = f' (wrapped by meson {reason})' |
| 1330 |
else: |
| 1331 |
cmd_type = '' |
| 1332 |
if target.depfile is not None: |
| 1333 |
depfile = target.get_dep_outname(elem.infilenames) |
| 1334 |
rel_dfile = os.path.join(self.get_target_dir(target), depfile) |
| 1335 |
abs_pdir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target)) |
| 1336 |
os.makedirs(abs_pdir, exist_ok=True) |
| 1337 |
elem.add_item('DEPFILE', rel_dfile) |
| 1338 |
if target.console: |
| 1339 |
elem.add_item('pool', 'console') |
| 1340 |
full_name = Path(target.subdir, target.name).as_posix() |
| 1341 |
elem.add_item('COMMAND', cmd) |
| 1342 |
elem.add_item('description', target.description.format(full_name) + cmd_type) |
| 1343 |
self.add_build(elem) |
| 1344 |
self.processed_targets.add(target.get_id()) |
| 1345 |
|
| 1346 |
def build_run_target_name(self, target: build.RunTarget) -> str: |
| 1347 |
if target.subproject != '': |
| 1348 |
subproject_prefix = f'{target.subproject}@@' |
| 1349 |
else: |
| 1350 |
subproject_prefix = '' |
| 1351 |
return f'{subproject_prefix}{target.name}' |
| 1352 |
|
| 1353 |
def generate_run_target(self, target: build.RunTarget) -> None: |
| 1354 |
target_name = self.build_run_target_name(target) |
| 1355 |
if not target.command: |
| 1356 |
# This is an alias target, it has no command, it just depends on |
| 1357 |
# other targets. |
| 1358 |
elem = NinjaBuildElement(self.all_outputs, target_name, 'phony', []) |
| 1359 |
else: |
| 1360 |
target_env = self.get_run_target_env(target) |
| 1361 |
_, _, cmd = self.eval_custom_target_command(target) |
| 1362 |
meson_exe_cmd, reason = self.as_meson_exe_cmdline(target.command[0], cmd[1:], |
| 1363 |
env=target_env, |
| 1364 |
verbose=True) |
| 1365 |
cmd_type = f' (wrapped by meson {reason})' if reason else '' |
| 1366 |
elem = self.create_phony_target(target_name, 'CUSTOM_COMMAND', []) |
| 1367 |
elem.add_item('COMMAND', meson_exe_cmd) |
| 1368 |
elem.add_item('description', f'Running external command {target.name}{cmd_type}') |
| 1369 |
elem.add_item('pool', 'console') |
| 1370 |
deps = self.get_paths_for_dep_outputs(target, target.get_dependencies()) |
| 1371 |
deps += self.get_target_depend_files(target) |
| 1372 |
elem.add_dep(deps) |
| 1373 |
self.add_build(elem) |
| 1374 |
self.processed_targets.add(target.get_id()) |
| 1375 |
|
| 1376 |
def generate_coverage_command(self, elem: NinjaBuildElement, outputs: T.List[str], |
| 1377 |
gcovr_exe: T.Optional[str], llvm_cov_exe: T.Optional[str]) -> None: |
| 1378 |
targets = self.build.get_targets().values() |
| 1379 |
use_llvm_cov = False |
| 1380 |
exe_args = [] |
| 1381 |
if gcovr_exe is not None: |
| 1382 |
exe_args += ['--gcov', gcovr_exe] |
| 1383 |
if llvm_cov_exe is not None: |
| 1384 |
exe_args += ['--llvm-cov', llvm_cov_exe] |
| 1385 |
|
| 1386 |
for target in targets: |
| 1387 |
if not isinstance(target, build.BuildTarget): |
| 1388 |
continue |
| 1389 |
for compiler in target.compilers.values(): |
| 1390 |
if compiler.get_id() == 'clang' and not compiler.info.is_darwin(): |
| 1391 |
use_llvm_cov = True |
| 1392 |
break |
| 1393 |
elem.add_item('COMMAND', self.environment.get_build_command() + |
| 1394 |
['--internal', 'coverage'] + |
| 1395 |
outputs + |
| 1396 |
[self.environment.get_source_dir(), |
| 1397 |
os.path.join(self.environment.get_source_dir(), |
| 1398 |
self.build.get_subproject_dir()), |
| 1399 |
self.environment.get_build_dir(), |
| 1400 |
self.environment.get_log_dir()] + |
| 1401 |
exe_args + |
| 1402 |
(['--use-llvm-cov'] if use_llvm_cov else [])) |
| 1403 |
|
| 1404 |
def generate_coverage_rules(self, gcovr_exe: T.Optional[str], gcovr_version: T.Optional[str], llvm_cov_exe: T.Optional[str]) -> None: |
| 1405 |
e = self.create_phony_target('coverage', 'CUSTOM_COMMAND', 'PHONY') |
| 1406 |
self.generate_coverage_command(e, [], gcovr_exe, llvm_cov_exe) |
| 1407 |
e.add_item('description', 'Generating coverage reports') |
| 1408 |
self.add_build(e) |
| 1409 |
self.generate_coverage_legacy_rules(gcovr_exe, gcovr_version, llvm_cov_exe) |
| 1410 |
|
| 1411 |
def generate_coverage_legacy_rules(self, gcovr_exe: T.Optional[str], gcovr_version: T.Optional[str], llvm_cov_exe: T.Optional[str]) -> None: |
| 1412 |
e = self.create_phony_target('coverage-html', 'CUSTOM_COMMAND', 'PHONY') |
| 1413 |
self.generate_coverage_command(e, ['--html'], gcovr_exe, llvm_cov_exe) |
| 1414 |
e.add_item('description', 'Generating HTML coverage report') |
| 1415 |
self.add_build(e) |
| 1416 |
|
| 1417 |
if gcovr_exe: |
| 1418 |
e = self.create_phony_target('coverage-xml', 'CUSTOM_COMMAND', 'PHONY') |
| 1419 |
self.generate_coverage_command(e, ['--xml'], gcovr_exe, llvm_cov_exe) |
| 1420 |
e.add_item('description', 'Generating XML coverage report') |
| 1421 |
self.add_build(e) |
| 1422 |
|
| 1423 |
e = self.create_phony_target('coverage-text', 'CUSTOM_COMMAND', 'PHONY') |
| 1424 |
self.generate_coverage_command(e, ['--text'], gcovr_exe, llvm_cov_exe) |
| 1425 |
e.add_item('description', 'Generating text coverage report') |
| 1426 |
self.add_build(e) |
| 1427 |
|
| 1428 |
if mesonlib.version_compare(gcovr_version, '>=4.2'): |
| 1429 |
e = self.create_phony_target('coverage-sonarqube', 'CUSTOM_COMMAND', 'PHONY') |
| 1430 |
self.generate_coverage_command(e, ['--sonarqube'], gcovr_exe, llvm_cov_exe) |
| 1431 |
e.add_item('description', 'Generating Sonarqube XML coverage report') |
| 1432 |
self.add_build(e) |
| 1433 |
|
| 1434 |
def generate_install(self) -> None: |
| 1435 |
self.create_install_data_files() |
| 1436 |
elem = self.create_phony_target('install', 'CUSTOM_COMMAND', 'PHONY') |
| 1437 |
elem.add_dep('all') |
| 1438 |
elem.add_item('DESC', 'Installing files') |
| 1439 |
elem.add_item('COMMAND', self.environment.get_build_command() + ['install', '--no-rebuild']) |
| 1440 |
elem.add_item('pool', 'console') |
| 1441 |
self.add_build(elem) |
| 1442 |
|
| 1443 |
def generate_tests(self) -> None: |
| 1444 |
self.serialize_tests() |
| 1445 |
cmd = self.environment.get_build_command(True) + ['test', '--no-rebuild'] |
| 1446 |
if not self.environment.coredata.optstore.get_value_for(OptionKey('stdsplit')): |
| 1447 |
cmd += ['--no-stdsplit'] |
| 1448 |
if self.environment.coredata.optstore.get_value_for(OptionKey('errorlogs')): |
| 1449 |
cmd += ['--print-errorlogs'] |
| 1450 |
elem = self.create_phony_target('test', 'CUSTOM_COMMAND', ['all', 'meson-test-prereq', 'PHONY']) |
| 1451 |
elem.add_item('COMMAND', cmd) |
| 1452 |
elem.add_item('DESC', 'Running all tests') |
| 1453 |
elem.add_item('pool', 'console') |
| 1454 |
self.add_build(elem) |
| 1455 |
|
| 1456 |
# And then benchmarks. |
| 1457 |
cmd = self.environment.get_build_command(True) + [ |
| 1458 |
'test', '--benchmark', '--logbase', |
| 1459 |
'benchmarklog', '--num-processes=1', '--no-rebuild'] |
| 1460 |
elem = self.create_phony_target('benchmark', 'CUSTOM_COMMAND', ['all', 'meson-benchmark-prereq', 'PHONY']) |
| 1461 |
elem.add_item('COMMAND', cmd) |
| 1462 |
elem.add_item('DESC', 'Running benchmark suite') |
| 1463 |
elem.add_item('pool', 'console') |
| 1464 |
self.add_build(elem) |
| 1465 |
|
| 1466 |
def generate_rules(self) -> None: |
| 1467 |
self.add_rule_comment(NinjaComment('Rules for module scanning.')) |
| 1468 |
self.generate_scanner_rules() |
| 1469 |
self.add_rule_comment(NinjaComment('Rules for compiling.')) |
| 1470 |
self.generate_compile_rules() |
| 1471 |
self.add_rule_comment(NinjaComment('Rules for linking.')) |
| 1472 |
self.generate_static_link_rules() |
| 1473 |
self.generate_dynamic_link_rules() |
| 1474 |
self.add_rule_comment(NinjaComment('Other rules')) |
| 1475 |
|
| 1476 |
# Ninja errors out if you have deps = gcc but no depfile, so we must |
| 1477 |
# have two rules for custom commands. |
| 1478 |
self.add_rule(NinjaRule('CUSTOM_COMMAND', ['$COMMAND'], [], '$DESC', |
| 1479 |
restat=True)) |
| 1480 |
self.add_rule(NinjaRule('CUSTOM_COMMAND_DEP', ['$COMMAND'], [], '$DESC', |
| 1481 |
deps='gcc', depfile='$DEPFILE', |
| 1482 |
restat=True)) |
| 1483 |
self.add_rule(NinjaRule('CUSTOM_COMMAND_MSVC_DEP', ['$COMMAND'], [], '$DESC', |
| 1484 |
deps='msvc', |
| 1485 |
restat=True)) |
| 1486 |
self.add_rule(NinjaRule('COPY_FILE', self.environment.get_build_command() + ['--internal', 'copy'], |
| 1487 |
['$in', '$out'], 'Copying $in to $out')) |
| 1488 |
|
| 1489 |
c = self.environment.get_build_command() + \ |
| 1490 |
['--internal', |
| 1491 |
'regenerate', |
| 1492 |
self.environment.get_source_dir(), |
| 1493 |
# Ninja always runs from the build_dir. This includes cases where the user moved the |
| 1494 |
# build directory and invalidated most references. Make sure it still regenerates. |
| 1495 |
'.'] |
| 1496 |
self.add_rule(NinjaRule('REGENERATE_BUILD', |
| 1497 |
c, [], |
| 1498 |
'Regenerating build files', |
| 1499 |
extra='generator = 1')) |
| 1500 |
|
| 1501 |
def add_rule_comment(self, comment: NinjaComment) -> None: |
| 1502 |
self.ninja.add_rule_comment(comment) |
| 1503 |
|
| 1504 |
def add_build_comment(self, comment: NinjaComment) -> None: |
| 1505 |
self.ninja.add_build_comment(comment) |
| 1506 |
|
| 1507 |
def add_rule(self, rule: NinjaRule) -> None: |
| 1508 |
self.ninja.add_rule(rule) |
| 1509 |
|
| 1510 |
def add_build(self, build: NinjaBuildElement) -> None: |
| 1511 |
self.ninja.add_build(build) |
| 1512 |
|
| 1513 |
def generate_phony(self) -> None: |
| 1514 |
self.add_build_comment(NinjaComment('Phony build target, always out of date')) |
| 1515 |
elem = NinjaBuildElement(self.all_outputs, 'PHONY', 'phony', '') |
| 1516 |
self.add_build(elem) |
| 1517 |
|
| 1518 |
def generate_jar_target(self, target: build.Jar) -> None: |
| 1519 |
fname = target.get_filename() |
| 1520 |
outname_rel = os.path.join(self.get_target_dir(target), fname) |
| 1521 |
src_list = target.get_sources() |
| 1522 |
resources = target.get_java_resources() |
| 1523 |
compiler = target.compilers['java'] |
| 1524 |
c = 'c' |
| 1525 |
m = 'm' |
| 1526 |
e = '' |
| 1527 |
f = 'f' |
| 1528 |
main_class = target.get_main_class() |
| 1529 |
if main_class != '': |
| 1530 |
e = 'e' |
| 1531 |
|
| 1532 |
# Add possible java generated files to src list |
| 1533 |
generated_sources = self.get_target_generated_sources(target) |
| 1534 |
gen_src_list = [] |
| 1535 |
for rel_src in generated_sources: |
| 1536 |
raw_src = File.from_built_relative(rel_src) |
| 1537 |
if rel_src.endswith('.java'): |
| 1538 |
gen_src_list.append(raw_src) |
| 1539 |
|
| 1540 |
compile_args = self.determine_java_compile_args(target, compiler) |
| 1541 |
class_list = self.generate_java_compile([*src_list, *gen_src_list], target, compiler, compile_args) |
| 1542 |
class_dep_list = [os.path.join(self.get_target_private_dir(target), i) for i in class_list] |
| 1543 |
manifest_path = os.path.join(self.get_target_private_dir(target), 'META-INF', 'MANIFEST.MF') |
| 1544 |
manifest_fullpath = os.path.join(self.environment.get_build_dir(), manifest_path) |
| 1545 |
os.makedirs(os.path.dirname(manifest_fullpath), exist_ok=True) |
| 1546 |
with open(manifest_fullpath, 'w', encoding='utf-8') as manifest: |
| 1547 |
if any(target.link_targets): |
| 1548 |
manifest.write('Class-Path: ') |
| 1549 |
cp_paths = [os.path.join(self.get_target_dir(l), l.get_filename()) for l in target.link_targets] |
| 1550 |
manifest.write(' '.join(cp_paths)) |
| 1551 |
manifest.write('\n') |
| 1552 |
jar_rule = 'java_LINKER' |
| 1553 |
commands = [c + m + e + f] |
| 1554 |
commands.append(manifest_path) |
| 1555 |
if e != '': |
| 1556 |
commands.append(main_class) |
| 1557 |
commands.append(self.get_target_filename(target)) |
| 1558 |
# Java compilation can produce an arbitrary number of output |
| 1559 |
# class files for a single source file. Thus tell jar to just |
| 1560 |
# grab everything in the final package. |
| 1561 |
commands += ['-C', self.get_target_private_dir(target), '.'] |
| 1562 |
elem = NinjaBuildElement(self.all_outputs, outname_rel, jar_rule, []) |
| 1563 |
elem.add_dep(class_dep_list) |
| 1564 |
if resources: |
| 1565 |
# Copy all resources into the root of the jar. |
| 1566 |
elem.add_orderdep(self.__generate_sources_structure(Path(self.get_target_private_dir(target)), resources)[0]) |
| 1567 |
elem.add_item('ARGS', commands) |
| 1568 |
self.add_build(elem) |
| 1569 |
# Create introspection information |
| 1570 |
self.create_target_source_introspection(target, compiler, compile_args, src_list, gen_src_list) |
| 1571 |
|
| 1572 |
def generate_cs_resource_tasks(self, target: build.BuildTarget) -> T.Tuple[T.List[str], T.List[str]]: |
| 1573 |
args = [] |
| 1574 |
deps = [] |
| 1575 |
for r in target.resources: |
| 1576 |
rel_sourcefile = os.path.join(self.build_to_src, target.subdir, r) |
| 1577 |
if r.endswith('.resources'): |
| 1578 |
a = '-resource:' + rel_sourcefile |
| 1579 |
elif r.endswith('.txt') or r.endswith('.resx'): |
| 1580 |
ofilebase = os.path.splitext(os.path.basename(r))[0] + '.resources' |
| 1581 |
ofilename = os.path.join(self.get_target_private_dir(target), ofilebase) |
| 1582 |
elem = NinjaBuildElement(self.all_outputs, ofilename, "CUSTOM_COMMAND", rel_sourcefile) |
| 1583 |
elem.add_item('COMMAND', ['resgen', rel_sourcefile, ofilename]) |
| 1584 |
elem.add_item('DESC', f'Compiling resource {rel_sourcefile}') |
| 1585 |
self.add_build(elem) |
| 1586 |
deps.append(ofilename) |
| 1587 |
a = '-resource:' + ofilename |
| 1588 |
else: |
| 1589 |
raise InvalidArguments(f'Unknown resource file {r}.') |
| 1590 |
args.append(a) |
| 1591 |
return args, deps |
| 1592 |
|
| 1593 |
def generate_cs_target(self, target: build.BuildTarget) -> None: |
| 1594 |
fname = target.get_filename() |
| 1595 |
outname_rel = os.path.join(self.get_target_dir(target), fname) |
| 1596 |
src_list = target.get_sources() |
| 1597 |
compiler = T.cast('CsCompiler', target.compilers['cs']) |
| 1598 |
rel_srcs = [os.path.normpath(s.rel_to_builddir(self.build_to_src)) for s in src_list] |
| 1599 |
deps = [] |
| 1600 |
commands = self.generate_basic_compiler_args(target, compiler) |
| 1601 |
commands += target.extra_args['cs'] |
| 1602 |
if isinstance(target, build.Executable): |
| 1603 |
commands.append('-target:exe') |
| 1604 |
elif isinstance(target, build.SharedLibrary): |
| 1605 |
commands.append('-target:library') |
| 1606 |
else: |
| 1607 |
raise MesonException('Unknown C# target type.') |
| 1608 |
(resource_args, resource_deps) = self.generate_cs_resource_tasks(target) |
| 1609 |
commands += resource_args |
| 1610 |
deps += resource_deps |
| 1611 |
commands += compiler.get_output_args(outname_rel) |
| 1612 |
for l in target.link_targets: |
| 1613 |
lname = os.path.join(self.get_target_dir(l), l.get_filename()) |
| 1614 |
commands += compiler.get_link_args(lname) |
| 1615 |
deps.append(lname) |
| 1616 |
if '-g' in commands: |
| 1617 |
outputs = [outname_rel, outname_rel + '.mdb'] |
| 1618 |
else: |
| 1619 |
outputs = [outname_rel] |
| 1620 |
generated_sources = self.get_target_generated_sources(target) |
| 1621 |
generated_rel_srcs = [] |
| 1622 |
for rel_src in generated_sources: |
| 1623 |
if rel_src.lower().endswith('.cs'): |
| 1624 |
generated_rel_srcs.append(os.path.normpath(rel_src)) |
| 1625 |
deps.append(os.path.normpath(rel_src)) |
| 1626 |
|
| 1627 |
for dep in target.get_external_deps(): |
| 1628 |
commands.extend_direct(dep.get_link_args()) |
| 1629 |
|
| 1630 |
elem = NinjaBuildElement(self.all_outputs, outputs, self.compiler_to_rule_name(compiler), rel_srcs + generated_rel_srcs) |
| 1631 |
elem.add_dep(deps) |
| 1632 |
elem.add_item('ARGS', commands) |
| 1633 |
self.add_build(elem) |
| 1634 |
|
| 1635 |
self.create_target_source_introspection(target, compiler, commands, rel_srcs, generated_rel_srcs) |
| 1636 |
|
| 1637 |
def determine_java_compile_args(self, target: build.Jar, compiler: Compiler) -> T.List[str]: |
| 1638 |
args = self.generate_basic_compiler_args(target, compiler) |
| 1639 |
args += target.get_java_args() |
| 1640 |
args += compiler.get_output_args(self.get_target_private_dir(target)) |
| 1641 |
args += target.get_classpath_args() |
| 1642 |
curdir = target.get_subdir() |
| 1643 |
sourcepaths = [os.path.join(self.build_to_src, curdir)] |
| 1644 |
sourcepaths.append(os.path.normpath(curdir)) |
| 1645 |
for i in target.include_dirs: |
| 1646 |
sourcepaths.extend(i.abs_string_list(self.source_dir, self.build_dir)) |
| 1647 |
args += ['-sourcepath', os.pathsep.join(sourcepaths)] |
| 1648 |
return list(args) |
| 1649 |
|
| 1650 |
def generate_java_compile(self, srcs: T.List[File], target: build.BuildTarget, compiler: Compiler, args: T.List[str]) -> T.List[str]: |
| 1651 |
deps = [os.path.join(self.get_target_dir(l), l.get_filename()) for l in target.link_targets] |
| 1652 |
generated_sources = self.get_target_generated_sources(target) |
| 1653 |
for rel_src in generated_sources: |
| 1654 |
if rel_src.endswith('.java'): |
| 1655 |
deps.append(rel_src) |
| 1656 |
|
| 1657 |
rel_srcs = [] |
| 1658 |
plain_class_paths = [] |
| 1659 |
rel_objs = [] |
| 1660 |
for src in srcs: |
| 1661 |
rel_src = src.rel_to_builddir(self.build_to_src) |
| 1662 |
rel_srcs.append(rel_src) |
| 1663 |
|
| 1664 |
# Preserve any additional path components on top of the target's subdir |
| 1665 |
plain_class_path = os.path.relpath(src.relative_name(), target.get_subdir()) |
| 1666 |
plain_class_path = plain_class_path[:-4] + 'class' |
| 1667 |
plain_class_paths.append(plain_class_path) |
| 1668 |
rel_obj = os.path.join(self.get_target_private_dir(target), plain_class_path) |
| 1669 |
rel_objs.append(rel_obj) |
| 1670 |
element = NinjaBuildElement(self.all_outputs, rel_objs, self.compiler_to_rule_name(compiler), rel_srcs) |
| 1671 |
element.add_dep(deps) |
| 1672 |
element.add_item('ARGS', args) |
| 1673 |
element.add_item('FOR_JAR', self.get_target_filename(target)) |
| 1674 |
self.add_build(element) |
| 1675 |
return plain_class_paths |
| 1676 |
|
| 1677 |
def generate_java_link(self) -> None: |
| 1678 |
rule = 'java_LINKER' |
| 1679 |
command = ['jar', '$ARGS'] |
| 1680 |
description = 'Creating JAR $out' |
| 1681 |
self.add_rule(NinjaRule(rule, command, [], description)) |
| 1682 |
|
| 1683 |
def determine_dep_vapis(self, target: build.BuildTarget) -> T.List[str]: |
| 1684 |
""" |
| 1685 |
Peek into the sources of BuildTargets we're linking with, and if any of |
| 1686 |
them was built with Vala, assume that it also generated a .vapi file of |
| 1687 |
the same name as the BuildTarget and return the path to it relative to |
| 1688 |
the build directory. |
| 1689 |
""" |
| 1690 |
result: OrderedSet[str] = OrderedSet() |
| 1691 |
for dep in itertools.chain(target.link_targets, target.link_whole_targets): |
| 1692 |
if not (isinstance(dep, build.BuildTarget) and dep.is_linkable_target()): |
| 1693 |
continue |
| 1694 |
for i in dep.sources: |
| 1695 |
if i.split('.')[-1] in compilers.lang_suffixes['vala']: |
| 1696 |
if dep.vala_vapi is not None: |
| 1697 |
vapiname = dep.vala_vapi |
| 1698 |
fullname = os.path.join(self.get_target_dir(dep), vapiname) |
| 1699 |
result.add(fullname) |
| 1700 |
break |
| 1701 |
return list(result) |
| 1702 |
|
| 1703 |
def split_vala_sources(self, t: build.BuildTarget) -> \ |
| 1704 |
T.Tuple[T.MutableMapping[str, build.TargetSources], T.MutableMapping[str, build.TargetSources], |
| 1705 |
T.MutableMapping[str, File], T.MutableMapping[str, build.TargetSources]]: |
| 1706 |
""" |
| 1707 |
Splits the target's sources into .vala, .gs, .vapi, and other sources. |
| 1708 |
Handles both preexisting and generated sources. |
| 1709 |
|
| 1710 |
Returns a tuple (vala, vapi, others) each of which is a dictionary with |
| 1711 |
the keys being the path to the file (relative to the build directory) |
| 1712 |
and the value being the object that generated or represents the file. |
| 1713 |
""" |
| 1714 |
vala: T.MutableMapping[str, build.TargetSources] = OrderedDict() |
| 1715 |
vapi: T.MutableMapping[str, build.TargetSources] = OrderedDict() |
| 1716 |
others: T.MutableMapping[str, File] = OrderedDict() |
| 1717 |
othersgen: T.MutableMapping[str, build.TargetSources] = OrderedDict() |
| 1718 |
# Split preexisting sources |
| 1719 |
for s in t.get_sources(): |
| 1720 |
# BuildTarget sources are always mesonlib.File files which are |
| 1721 |
# either in the source root, or generated with configure_file and |
| 1722 |
# in the build root |
| 1723 |
if not isinstance(s, File): |
| 1724 |
raise InvalidArguments(f'All sources in target {t!r} must be of type mesonlib.File, not {s!r}') |
| 1725 |
f = s.rel_to_builddir(self.build_to_src) |
| 1726 |
if s.endswith(('.vala', '.gs')): |
| 1727 |
vala[f] = s |
| 1728 |
elif s.endswith('.vapi'): |
| 1729 |
vapi[f] = s |
| 1730 |
else: |
| 1731 |
others[f] = s |
| 1732 |
# Split generated sources |
| 1733 |
for gensrc in t.get_generated_sources(): |
| 1734 |
for s in gensrc.get_outputs(): |
| 1735 |
f = self.get_target_generated_dir(t, gensrc, s) |
| 1736 |
if s.endswith(('.vala', '.gs')): |
| 1737 |
gensrctype = vala |
| 1738 |
elif s.endswith('.vapi'): |
| 1739 |
gensrctype = vapi |
| 1740 |
# Generated non-Vala (C/C++) sources. Won't be used for |
| 1741 |
# generating the Vala compile rule below. |
| 1742 |
else: |
| 1743 |
gensrctype = othersgen |
| 1744 |
# Duplicate outputs are disastrous |
| 1745 |
if f in gensrctype and gensrctype[f] != gensrc: |
| 1746 |
msg = 'Duplicate output {0!r} from {1!r} {2!r}; ' \ |
| 1747 |
'conflicts with {0!r} from {4!r} {3!r}' \ |
| 1748 |
''.format(f, type(gensrc).__name__, gensrc.name, |
| 1749 |
gensrctype[f], type(gensrctype[f]).__name__) |
| 1750 |
raise InvalidArguments(msg) |
| 1751 |
# Store 'somefile.vala': GeneratedList (or CustomTarget) |
| 1752 |
gensrctype[f] = gensrc |
| 1753 |
return vala, vapi, others, othersgen |
| 1754 |
|
| 1755 |
def generate_vala_compile(self, target: build.BuildTarget) -> \ |
| 1756 |
T.Tuple[T.MutableMapping[str, File], T.MutableMapping[str, build.TargetSources], T.List[str]]: |
| 1757 |
"""Vala is compiled into C. Set up all necessary build steps here.""" |
| 1758 |
(vala_src, vapi_src, others, othersgen) = self.split_vala_sources(target) |
| 1759 |
extra_dep_files = [] |
| 1760 |
if not vala_src: |
| 1761 |
raise InvalidArguments(f'Vala library {target.name!r} has no Vala or Genie source files.') |
| 1762 |
|
| 1763 |
valac = target.compilers['vala'] |
| 1764 |
c_out_dir = self.get_target_private_dir(target) |
| 1765 |
# C files generated by valac |
| 1766 |
vala_c_src: T.List[str] = [] |
| 1767 |
# Files generated by valac |
| 1768 |
valac_outputs: T.List = [] |
| 1769 |
# All sources that are passed to valac on the commandline |
| 1770 |
all_files = list(vapi_src) |
| 1771 |
# Passed as --basedir |
| 1772 |
srcbasedir = os.path.join(self.build_to_src, target.get_subdir()) |
| 1773 |
for (vala_file, gensrc) in vala_src.items(): |
| 1774 |
all_files.append(vala_file) |
| 1775 |
# Figure out where the Vala compiler will write the compiled C file |
| 1776 |
# |
| 1777 |
# If the Vala file is in a subdir of the build dir (in our case |
| 1778 |
# because it was generated/built by something else), and is also |
| 1779 |
# a subdir of --basedir (because the builddir is in the source |
| 1780 |
# tree, and the target subdir is the source root), the subdir |
| 1781 |
# components from the source root till the private builddir will be |
| 1782 |
# duplicated inside the private builddir. Otherwise, just the |
| 1783 |
# basename will be used. |
| 1784 |
# |
| 1785 |
# If the Vala file is outside the build directory, the paths from |
| 1786 |
# the --basedir till the subdir will be duplicated inside the |
| 1787 |
# private builddir. |
| 1788 |
if isinstance(gensrc, (build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)) or gensrc.is_built: |
| 1789 |
vala_c_file = os.path.splitext(os.path.basename(vala_file))[0] + '.c' |
| 1790 |
# Check if the vala file is in a subdir of --basedir |
| 1791 |
abs_srcbasedir = os.path.join(self.environment.get_source_dir(), target.get_subdir()) |
| 1792 |
abs_vala_file = os.path.join(self.environment.get_build_dir(), vala_file) |
| 1793 |
if is_parent_path(abs_srcbasedir, abs_vala_file): |
| 1794 |
vala_c_subdir = PurePath(abs_vala_file).parent.relative_to(abs_srcbasedir) |
| 1795 |
vala_c_file = os.path.join(str(vala_c_subdir), vala_c_file) |
| 1796 |
else: |
| 1797 |
path_to_target = os.path.join(self.build_to_src, target.get_subdir()) |
| 1798 |
if vala_file.startswith(path_to_target): |
| 1799 |
vala_c_file = os.path.splitext(os.path.relpath(vala_file, path_to_target))[0] + '.c' |
| 1800 |
else: |
| 1801 |
vala_c_file = os.path.splitext(os.path.basename(vala_file))[0] + '.c' |
| 1802 |
# All this will be placed inside the c_out_dir |
| 1803 |
vala_c_file = os.path.join(c_out_dir, vala_c_file) |
| 1804 |
vala_c_src.append(vala_c_file) |
| 1805 |
valac_outputs.append(vala_c_file) |
| 1806 |
|
| 1807 |
args = self.generate_basic_compiler_args(target, valac) |
| 1808 |
b_colorout = self.get_target_option(target, 'b_colorout') |
| 1809 |
assert isinstance(b_colorout, str) |
| 1810 |
args += valac.get_colorout_args(b_colorout) |
| 1811 |
# Tell Valac to output everything in our private directory. Sadly this |
| 1812 |
# means it will also preserve the directory components of Vala sources |
| 1813 |
# found inside the build tree (generated sources). |
| 1814 |
args += ['--directory', c_out_dir] |
| 1815 |
args += ['--basedir', srcbasedir] |
| 1816 |
if target.is_linkable_target(): |
| 1817 |
assert isinstance(target, build.LinkableTarget) |
| 1818 |
# Library name |
| 1819 |
args += ['--library', target.name] |
| 1820 |
# Outputted header |
| 1821 |
if target.vala_header is not None: |
| 1822 |
hname = os.path.join(self.get_target_dir(target), target.vala_header) |
| 1823 |
args += ['--header', hname] |
| 1824 |
if self.is_unity(target): |
| 1825 |
# Without this the declarations will get duplicated in the .c |
| 1826 |
# files and cause a build failure when all of them are |
| 1827 |
# #include-d in one .c file. |
| 1828 |
# https://github.com/mesonbuild/meson/issues/1969 |
| 1829 |
args += ['--use-header'] |
| 1830 |
valac_outputs.append(hname) |
| 1831 |
# Outputted vapi file |
| 1832 |
if target.vala_vapi is not None: |
| 1833 |
vapiname = os.path.join(self.get_target_dir(target), target.vala_vapi) |
| 1834 |
# Force valac to write the vapi and gir files in the target build dir. |
| 1835 |
# Without this, it will write it inside c_out_dir |
| 1836 |
args += ['--vapi', os.path.join('..', target.vala_vapi)] |
| 1837 |
valac_outputs.append(vapiname) |
| 1838 |
# Generate GIR if requested |
| 1839 |
if target.vala_gir is not None: |
| 1840 |
girname = os.path.join(self.get_target_dir(target), target.vala_gir) |
| 1841 |
args += ['--gir', os.path.join('..', target.vala_gir)] |
| 1842 |
valac_outputs.append(girname) |
| 1843 |
shared_target = target.get('shared') |
| 1844 |
if isinstance(shared_target, build.SharedLibrary): |
| 1845 |
args += ['--shared-library', shared_target.get_filename()] |
| 1846 |
# Detect gresources and add --gresources/--gresourcesdir arguments for each |
| 1847 |
gres_dirs = [] |
| 1848 |
for gensrc in othersgen.values(): |
| 1849 |
if isinstance(gensrc, modules.GResourceTarget): |
| 1850 |
gres_xml, = self.get_custom_target_sources(gensrc) |
| 1851 |
args += ['--gresources=' + gres_xml] |
| 1852 |
for source_dir in gensrc.source_dirs: |
| 1853 |
gres_dirs += [source_dir] |
| 1854 |
# Ensure that resources are built before vala sources |
| 1855 |
# This is required since vala code using [GtkTemplate] effectively depends on .ui files |
| 1856 |
# GResourceHeaderTarget is not suitable due to lacking depfile |
| 1857 |
gres_c, = gensrc.get_outputs() |
| 1858 |
extra_dep_files += [os.path.join(self.get_target_dir(gensrc), gres_c)] |
| 1859 |
for gres_dir in OrderedSet(gres_dirs): |
| 1860 |
args += [f'--gresourcesdir={gres_dir}'] |
| 1861 |
dependency_vapis = self.determine_dep_vapis(target) |
| 1862 |
extra_dep_files += dependency_vapis |
| 1863 |
extra_dep_files.extend(self.get_target_depend_files(target)) |
| 1864 |
args += target.get_extra_args('vala') |
| 1865 |
element = NinjaBuildElement(self.all_outputs, valac_outputs, |
| 1866 |
self.compiler_to_rule_name(valac), |
| 1867 |
all_files + dependency_vapis) |
| 1868 |
element.add_item('ARGS', args) |
| 1869 |
depfile = valac.depfile_for_object(os.path.join(self.get_target_dir(target), target.name)) |
| 1870 |
element.add_item('DEPFILE', depfile) |
| 1871 |
element.add_dep(extra_dep_files) |
| 1872 |
self.add_build(element) |
| 1873 |
self.create_target_source_introspection(target, valac, args, all_files, []) |
| 1874 |
return others, othersgen, vala_c_src |
| 1875 |
|
| 1876 |
def generate_cython_transpile(self, target: build.BuildTarget) -> \ |
| 1877 |
T.Tuple[T.MutableMapping[str, File], T.MutableMapping[str, build.TargetSources], T.List[str]]: |
| 1878 |
"""Generate rules for transpiling Cython files to C or C++""" |
| 1879 |
|
| 1880 |
static_sources: T.MutableMapping[str, File] = OrderedDict() |
| 1881 |
generated_sources: T.MutableMapping[str, build.TargetSources] = OrderedDict() |
| 1882 |
cython_sources: T.List[str] = [] |
| 1883 |
|
| 1884 |
cython = target.compilers['cython'] |
| 1885 |
|
| 1886 |
args: T.List[str] = [] |
| 1887 |
args += cython.get_always_args() |
| 1888 |
debug = self.get_target_option(target, 'debug') |
| 1889 |
assert isinstance(debug, bool) |
| 1890 |
args += cython.get_debug_args(debug) |
| 1891 |
optimization = self.get_target_option(target, 'optimization') |
| 1892 |
assert isinstance(optimization, str) |
| 1893 |
args += cython.get_optimization_args(optimization) |
| 1894 |
args += cython.get_option_compile_args(target, target.subproject) |
| 1895 |
args += cython.get_option_std_args(target, target.subproject) |
| 1896 |
args += self.build.get_global_args(cython, target) |
| 1897 |
args += self.build.get_project_args(cython, target) |
| 1898 |
args += target.get_extra_args('cython') |
| 1899 |
|
| 1900 |
ext = self.get_target_option(target, OptionKey('cython_language', machine=target.for_machine)) |
| 1901 |
|
| 1902 |
pyx_sources = [] # Keep track of sources we're adding to build |
| 1903 |
pyx_count = 0 |
| 1904 |
for src in target.get_sources(): |
| 1905 |
if src.endswith('.pyx'): |
| 1906 |
pyx_count += 1 |
| 1907 |
for gen in target.get_generated_sources(): |
| 1908 |
for ssrc in gen.get_outputs(): |
| 1909 |
if ssrc.endswith('.pyx'): |
| 1910 |
pyx_count += 1 |
| 1911 |
|
| 1912 |
for src in target.get_sources(): |
| 1913 |
if src.endswith('.pyx'): |
| 1914 |
# Use basename to avoid too nested targets which can cause a |
| 1915 |
# problem with MAX_PATH on Windows |
| 1916 |
outname = os.path.basename(src.fname) if pyx_count == 1 else src.fname |
| 1917 |
output = os.path.join(self.get_target_private_dir(target), f'{outname}.{ext}') |
| 1918 |
element = NinjaBuildElement( |
| 1919 |
self.all_outputs, [output], |
| 1920 |
self.compiler_to_rule_name(cython), |
| 1921 |
[src.absolute_path(self.environment.get_source_dir(), self.environment.get_build_dir())]) |
| 1922 |
element.add_item('ARGS', args) |
| 1923 |
self.add_build(element) |
| 1924 |
# TODO: introspection? |
| 1925 |
cython_sources.append(output) |
| 1926 |
pyx_sources.append(element) |
| 1927 |
else: |
| 1928 |
static_sources[src.rel_to_builddir(self.build_to_src)] = src |
| 1929 |
|
| 1930 |
header_deps = [] # Keep track of generated headers for those sources |
| 1931 |
for gen in target.get_generated_sources(): |
| 1932 |
if isinstance(gen, GeneratedList): |
| 1933 |
builddir = self.get_target_private_dir(target) |
| 1934 |
else: |
| 1935 |
builddir = self.get_target_dir(gen) |
| 1936 |
for ssrc in gen.get_outputs(): |
| 1937 |
ssrc = os.path.join(builddir, ssrc) |
| 1938 |
if ssrc.endswith('.pyx'): |
| 1939 |
# Use basename to avoid too nested targets which can cause |
| 1940 |
# a problem with MAX_PATH on Windows |
| 1941 |
outname = os.path.basename(ssrc) if pyx_count == 1 else ssrc |
| 1942 |
output = os.path.join(self.get_target_private_dir(target), f'{outname}.{ext}') |
| 1943 |
element = NinjaBuildElement( |
| 1944 |
self.all_outputs, [output], |
| 1945 |
self.compiler_to_rule_name(cython), |
| 1946 |
[ssrc]) |
| 1947 |
element.add_item('ARGS', args) |
| 1948 |
self.add_build(element) |
| 1949 |
pyx_sources.append(element) |
| 1950 |
# TODO: introspection? |
| 1951 |
cython_sources.append(output) |
| 1952 |
else: |
| 1953 |
generated_sources[ssrc] = mesonlib.File.from_built_file(builddir, ssrc) |
| 1954 |
# Following logic in L883-900 where we determine whether to add generated source |
| 1955 |
# as a header(order-only) dep to the .so compilation rule |
| 1956 |
if not compilers.is_source(ssrc) and \ |
| 1957 |
not compilers.is_object(ssrc) and \ |
| 1958 |
not compilers.is_library(ssrc) and \ |
| 1959 |
not modules.is_module_library(ssrc): |
| 1960 |
header_deps.append(ssrc) |
| 1961 |
for source in pyx_sources: |
| 1962 |
source.add_orderdep(header_deps) |
| 1963 |
|
| 1964 |
return static_sources, generated_sources, cython_sources |
| 1965 |
|
| 1966 |
def _generate_copy_target(self, src: FileOrString, output: Path) -> None: |
| 1967 |
"""Create a target to copy a source file from one location to another.""" |
| 1968 |
if isinstance(src, File): |
| 1969 |
instr = src.absolute_path(self.environment.source_dir, self.environment.build_dir) |
| 1970 |
else: |
| 1971 |
instr = src |
| 1972 |
elem = NinjaBuildElement(self.all_outputs, [str(output)], 'COPY_FILE', [instr]) |
| 1973 |
elem.add_orderdep(instr) |
| 1974 |
self.add_build(elem) |
| 1975 |
|
| 1976 |
def __generate_sources_structure(self, root: Path, structured_sources: build.StructuredSources, |
| 1977 |
main_file_ext: T.Union[str, T.Tuple[str, ...]] = tuple(), |
| 1978 |
) -> T.Tuple[T.List[str], T.Optional[str]]: |
| 1979 |
first_file: T.Optional[str] = None |
| 1980 |
orderdeps: T.List[str] = [] |
| 1981 |
for path, files in structured_sources.sources.items(): |
| 1982 |
for file in files: |
| 1983 |
if isinstance(file, File): |
| 1984 |
out = root / path / Path(file.fname).name |
| 1985 |
self._generate_copy_target(file, out) |
| 1986 |
out_s = str(out) |
| 1987 |
orderdeps.append(out_s) |
| 1988 |
if first_file is None and out_s.endswith(main_file_ext): |
| 1989 |
first_file = out_s |
| 1990 |
else: |
| 1991 |
for f in file.get_outputs(): |
| 1992 |
out = root / path / f |
| 1993 |
out_s = str(out) |
| 1994 |
orderdeps.append(out_s) |
| 1995 |
self._generate_copy_target(str(Path(file.subdir) / f), out) |
| 1996 |
if first_file is None and out_s.endswith(main_file_ext): |
| 1997 |
first_file = out_s |
| 1998 |
return orderdeps, first_file |
| 1999 |
|
| 2000 |
def _add_rust_project_entry(self, name: str, main_rust_file: str, args: CompilerArgs, |
| 2001 |
crate_type: str, target_name: str, |
| 2002 |
from_subproject: bool, proc_macro_dylib_path: T.Optional[str], |
| 2003 |
deps: T.List[RustDep]) -> None: |
| 2004 |
raw_edition: T.Optional[str] = mesonlib.first(reversed(args), lambda x: x.startswith('--edition')) |
| 2005 |
edition = '2015' if not raw_edition else raw_edition.split('=', 1)[-1] |
| 2006 |
|
| 2007 |
cfg: T.List[str] = [] |
| 2008 |
arg_itr: T.Iterator[str] = iter(args) |
| 2009 |
for arg in arg_itr: |
| 2010 |
if arg == '--cfg': |
| 2011 |
cfg.append(next(arg_itr)) |
| 2012 |
elif arg.startswith('--cfg'): |
| 2013 |
cfg.append(arg[len('--cfg'):]) |
| 2014 |
|
| 2015 |
crate = RustCrate( |
| 2016 |
len(self.rust_crates), |
| 2017 |
self._get_rust_crate_name(name), |
| 2018 |
main_rust_file, |
| 2019 |
crate_type, |
| 2020 |
target_name, |
| 2021 |
T.cast('RUST_EDITIONS', edition), |
| 2022 |
deps, |
| 2023 |
cfg, |
| 2024 |
is_workspace_member=not from_subproject, |
| 2025 |
proc_macro_dylib_path=proc_macro_dylib_path, |
| 2026 |
) |
| 2027 |
|
| 2028 |
self.rust_crates[name] = crate |
| 2029 |
|
| 2030 |
@staticmethod |
| 2031 |
def _get_rust_crate_name(target_name: str) -> str: |
| 2032 |
# Rustc replaces - with _. spaces or dots are not allowed, so we replace them with underscores |
| 2033 |
# Also +SUFFIX is dropped, which can be used to distinguish host from build crates |
| 2034 |
crate_name = target_name.replace('-', '_').replace(' ', '_').replace('.', '_') |
| 2035 |
return crate_name.split('+', 1)[0] |
| 2036 |
|
| 2037 |
@staticmethod |
| 2038 |
def _get_rust_dependency_name(target: build.BuildTarget, dependency: build.BuildTarget) -> str: |
| 2039 |
crate_name_raw = target.rust_dependency_map.get(dependency.name, None) |
| 2040 |
if crate_name_raw is None: |
| 2041 |
dependency_crate_name = NinjaBackend._get_rust_crate_name(dependency.name) |
| 2042 |
crate_name_raw = target.rust_dependency_map.get(dependency_crate_name, dependency.name) |
| 2043 |
return NinjaBackend._get_rust_crate_name(crate_name_raw) |
| 2044 |
|
| 2045 |
def generate_rust_sources(self, target: build.BuildTarget) -> T.Tuple[T.List[str], str]: |
| 2046 |
orderdeps: T.List[str] = [] |
| 2047 |
|
| 2048 |
# Rust compiler takes only the main file as input and |
| 2049 |
# figures out what other files are needed via import |
| 2050 |
# statements and magic. |
| 2051 |
main_rust_file: T.Optional[str] = None |
| 2052 |
if target.structured_sources: |
| 2053 |
if target.structured_sources.needs_copy(): |
| 2054 |
_ods, main_rust_file = self.__generate_sources_structure(Path( |
| 2055 |
self.get_target_private_dir(target)) / 'structured', target.structured_sources, '.rs') |
| 2056 |
if main_rust_file is None: |
| 2057 |
raise MesonException('Could not find a rust file to treat as the main file for ', target.name) |
| 2058 |
else: |
| 2059 |
# The only way to get here is to have only files in the "root" |
| 2060 |
# positional argument, which are all generated into the same |
| 2061 |
# directory |
| 2062 |
for g in target.structured_sources.sources['']: |
| 2063 |
if isinstance(g, File): |
| 2064 |
if g.endswith('.rs'): |
| 2065 |
main_rust_file = g.rel_to_builddir(self.build_to_src) |
| 2066 |
elif isinstance(g, GeneratedList): |
| 2067 |
for h in g.get_outputs(): |
| 2068 |
if h.endswith('.rs'): |
| 2069 |
main_rust_file = os.path.join(self.get_target_private_dir(target), h) |
| 2070 |
break |
| 2071 |
else: |
| 2072 |
for h in g.get_outputs(): |
| 2073 |
if h.endswith('.rs'): |
| 2074 |
main_rust_file = os.path.join(g.get_builddir(), h) |
| 2075 |
break |
| 2076 |
if main_rust_file is not None: |
| 2077 |
break |
| 2078 |
|
| 2079 |
_ods = [] |
| 2080 |
for f in target.structured_sources.as_list(): |
| 2081 |
if isinstance(f, File): |
| 2082 |
_ods.append(f.rel_to_builddir(self.build_to_src)) |
| 2083 |
else: |
| 2084 |
_ods.extend([os.path.join(self.build_to_src, f.subdir, s) |
| 2085 |
for s in f.get_outputs()]) |
| 2086 |
self.all_structured_sources.update(_ods) |
| 2087 |
orderdeps.extend(_ods) |
| 2088 |
return orderdeps, main_rust_file |
| 2089 |
|
| 2090 |
for i in target.get_sources(): |
| 2091 |
if main_rust_file is None and i.endswith('.rs'): |
| 2092 |
main_rust_file = i.rel_to_builddir(self.build_to_src) |
| 2093 |
for g in target.get_generated_sources(): |
| 2094 |
for i in g.get_outputs(): |
| 2095 |
if isinstance(g, GeneratedList): |
| 2096 |
fname = os.path.join(self.get_target_private_dir(target), i) |
| 2097 |
else: |
| 2098 |
fname = os.path.join(g.get_builddir(), i) |
| 2099 |
if main_rust_file is None and fname.endswith('.rs'): |
| 2100 |
main_rust_file = fname |
| 2101 |
orderdeps.append(fname) |
| 2102 |
|
| 2103 |
return orderdeps, main_rust_file |
| 2104 |
|
| 2105 |
def get_rust_compiler_args(self, target: build.BuildTarget, rustc: RustCompiler, src_crate_type: str, |
| 2106 |
depfile: T.Optional[str] = None) -> CompilerArgs: |
| 2107 |
# Compiler args for compiling this target |
| 2108 |
args = compilers.get_base_compile_args(target, rustc, self.environment) |
| 2109 |
|
| 2110 |
target_name = self.get_target_filename(target) |
| 2111 |
args.extend(['--crate-type', src_crate_type]) |
| 2112 |
|
| 2113 |
# If we're dynamically linking, add those arguments |
| 2114 |
if target.rust_crate_type in {'bin', 'dylib', 'cdylib'}: |
| 2115 |
args.extend(rustc.get_linker_always_args()) |
| 2116 |
args += compilers.get_base_link_args(target, rustc, self.environment) |
| 2117 |
|
| 2118 |
args += self.get_target_type_link_args(target, rustc) |
| 2119 |
|
| 2120 |
if target.rust_crate_type in {'bin', 'dylib', 'cdylib'}: |
| 2121 |
args += rustc.get_build_link_args(target, self.build) |
| 2122 |
args += rustc.get_target_link_args(target) |
| 2123 |
|
| 2124 |
cargs = args + self.generate_basic_compiler_args(target, rustc) |
| 2125 |
cargs += ['--crate-name', self._get_rust_crate_name(target.name)] |
| 2126 |
if depfile: |
| 2127 |
cargs += rustc.get_dependency_gen_args(target_name, depfile) |
| 2128 |
cargs += rustc.get_output_args(target_name) |
| 2129 |
cargs += ['-C', 'metadata=' + target.get_id()] |
| 2130 |
cargs += target.get_extra_args('rust') |
| 2131 |
return cargs |
| 2132 |
|
| 2133 |
def get_rust_compiler_deps_and_args(self, target: build.BuildTarget, rustc: RustCompiler, |
| 2134 |
obj_list: T.List[str]) -> T.Tuple[T.List[str], T.List[RustDep], T.List[str]]: |
| 2135 |
deps: T.List[str] = [] |
| 2136 |
project_deps: T.List[RustDep] = [] |
| 2137 |
args: T.List[str] = [] |
| 2138 |
|
| 2139 |
def _link_library(libname: str, static: bool, bundle: bool = False) -> None: |
| 2140 |
orig_libname = libname |
| 2141 |
type_ = 'static' if static else 'dylib' |
| 2142 |
modifiers = [] |
| 2143 |
# Except with -Clink-arg, search is limited to the -L search paths |
| 2144 |
dir_, libname = os.path.split(libname) |
| 2145 |
linkdirs.add(dir_) |
| 2146 |
if not bundle and static: |
| 2147 |
modifiers.append('-bundle') |
| 2148 |
if rustc.has_verbatim(): |
| 2149 |
modifiers.append('+verbatim') |
| 2150 |
else: |
| 2151 |
libname = rustc.lib_file_to_l_arg(libname) |
| 2152 |
if libname is None: |
| 2153 |
raise MesonException(f"rustc does not implement '-l{type_}:+verbatim'; cannot link to '{orig_libname}' due to nonstandard name") |
| 2154 |
|
| 2155 |
if modifiers: |
| 2156 |
type_ += ':' + ','.join(modifiers) |
| 2157 |
args.append(f'-l{type_}={libname}') |
| 2158 |
|
| 2159 |
for o in obj_list: |
| 2160 |
args.append(f'-Clink-arg={o}') |
| 2161 |
deps.append(o) |
| 2162 |
|
| 2163 |
deps.extend([self.get_dependency_filename(t) for t in target.link_depends]) |
| 2164 |
|
| 2165 |
linkdirs: OrderedSet[str] = OrderedSet() |
| 2166 |
external_deps = target.external_deps.copy() |
| 2167 |
target_deps = target.get_dependencies() |
| 2168 |
for d in target_deps: |
| 2169 |
# rlibs only store -l flags, not -L; help out rustc and always |
| 2170 |
# add the -L flag, in case it's needed to find non-bundled |
| 2171 |
# dependencies of an rlib. At this point we don't have |
| 2172 |
# information on whether this is a direct dependency (which |
| 2173 |
# might use -Clink-arg= below) or an indirect one, so always |
| 2174 |
# add to linkdirs. |
| 2175 |
linkdirs.add(self.get_target_dir(d)) |
| 2176 |
deps.append(self.get_dependency_filename(d)) |
| 2177 |
if isinstance(d, build.StaticLibrary): |
| 2178 |
external_deps.extend(d.external_deps) |
| 2179 |
if d.uses_rust_abi(): |
| 2180 |
if d not in target.link_targets and d not in target.link_whole_targets: |
| 2181 |
# Indirect Rust ABI dependency, we only need its path in linkdirs. |
| 2182 |
continue |
| 2183 |
assert isinstance(d, build.BuildTarget) |
| 2184 |
# specify `extern CRATE_NAME=OUTPUT_FILE` for each Rust |
| 2185 |
# dependency, so that collisions with libraries in rustc's |
| 2186 |
# sysroot don't cause ambiguity |
| 2187 |
d_name = self._get_rust_dependency_name(target, d) |
| 2188 |
args += ['--extern', '{}={}'.format(d_name, self.get_target_filename(d))] |
| 2189 |
project_deps.append(RustDep(d_name, self.rust_crates[d.name].order)) |
| 2190 |
continue |
| 2191 |
|
| 2192 |
# Link a C ABI library |
| 2193 |
|
| 2194 |
# Pass native libraries directly to the linker with "-C link-arg" |
| 2195 |
# because rustc's "-l:+verbatim=" is not portable and we cannot rely |
| 2196 |
# on linker to find the right library without using verbatim filename. |
| 2197 |
# For example "-lfoo" won't find "foo.so" in the case name_prefix set |
| 2198 |
# to "", or would always pick the shared library when both "libfoo.so" |
| 2199 |
# and "libfoo.a" are available. |
| 2200 |
# See https://doc.rust-lang.org/rustc/command-line-arguments.html#linking-modifiers-verbatim. |
| 2201 |
# |
| 2202 |
# However, rustc static linker (rlib and staticlib) requires using |
| 2203 |
# "-l" argument and does not rely on platform specific dynamic linker. |
| 2204 |
lib = self.get_target_filename_for_linking(d) |
| 2205 |
link_whole = d in target.link_whole_targets |
| 2206 |
if isinstance(target, build.StaticLibrary) or (isinstance(target, build.Executable) and rustc.get_crt_static()): |
| 2207 |
static = isinstance(d, build.StaticLibrary) |
| 2208 |
_link_library(lib, static, bundle=link_whole) |
| 2209 |
elif link_whole: |
| 2210 |
link_whole_args = rustc.linker.get_link_whole_for([lib]) |
| 2211 |
args += [f'-Clink-arg={a}' for a in link_whole_args] |
| 2212 |
else: |
| 2213 |
args.append(f'-Clink-arg={lib}') |
| 2214 |
|
| 2215 |
for e in external_deps: |
| 2216 |
prev: T.Optional[str] = None |
| 2217 |
for prev, a in lookbehind(e.get_link_args()): |
| 2218 |
if prev == '-framework': |
| 2219 |
args.append(f'-lframework={a}') |
| 2220 |
continue |
| 2221 |
elif a.startswith('-L'): |
| 2222 |
args.append(a) |
| 2223 |
continue |
| 2224 |
elif a.startswith('-F'): |
| 2225 |
path = a[2:] |
| 2226 |
args.append(f'-Lframework={path}') |
| 2227 |
continue |
| 2228 |
elif a == '-framework': |
| 2229 |
# handled once the framework name is available |
| 2230 |
continue |
| 2231 |
elif is_library(a): |
| 2232 |
if isinstance(target, build.StaticLibrary): |
| 2233 |
static = a.endswith(('.a', '.lib')) |
| 2234 |
_link_library(a, static) |
| 2235 |
continue |
| 2236 |
|
| 2237 |
dir_, _ = os.path.split(a) |
| 2238 |
linkdirs.add(dir_) |
| 2239 |
|
| 2240 |
args.append(f'-Clink-arg={a}') |
| 2241 |
|
| 2242 |
for d in linkdirs: |
| 2243 |
d = d or '.' |
| 2244 |
args.append(f'-L{d}') |
| 2245 |
|
| 2246 |
# Because of the way rustc links, this must come after any potential |
| 2247 |
# library need to link with their stdlibs (C++ and Fortran, for example) |
| 2248 |
args.extend(f'-Clink-arg={a}' for a in target.get_used_stdlib_args('rust')) |
| 2249 |
|
| 2250 |
has_shared_deps = any(isinstance(dep, build.SharedLibrary) for dep in target_deps) |
| 2251 |
has_rust_shared_deps = any(isinstance(dep, build.SharedLibrary) and dep.uses_rust() |
| 2252 |
and dep.rust_crate_type == 'dylib' |
| 2253 |
for dep in target_deps) |
| 2254 |
|
| 2255 |
if target.rust_crate_type in {'dylib', 'proc-macro'}: |
| 2256 |
# also add prefer-dynamic if any of the Rust libraries we link |
| 2257 |
# against are dynamic or this is a dynamic library itself, |
| 2258 |
# otherwise we'll end up with multiple implementations of libstd. |
| 2259 |
has_rust_shared_deps = True |
| 2260 |
elif self.get_target_option(target, 'rust_dynamic_std'): |
| 2261 |
if target.rust_crate_type == 'staticlib': |
| 2262 |
# staticlib crates always include a copy of the Rust libstd, |
| 2263 |
# therefore it is not possible to also link it dynamically. |
| 2264 |
# The options to avoid this (-Z staticlib-allow-rdylib-deps and |
| 2265 |
# -Z staticlib-prefer-dynamic) are not yet stable; alternatively, |
| 2266 |
# one could use "--emit obj" (implemented in the pull request at |
| 2267 |
# https://github.com/mesonbuild/meson/pull/11213) or "--emit rlib" |
| 2268 |
# (officially not recommended for linking with C programs). |
| 2269 |
raise MesonException('rust_dynamic_std does not support staticlib crates yet') |
| 2270 |
# want libstd as a shared dep |
| 2271 |
has_rust_shared_deps = True |
| 2272 |
|
| 2273 |
# Add link args specific to this BuildTarget type that must not be overridden by dependencies |
| 2274 |
args += self.get_target_type_link_args_post_dependencies(target, rustc) |
| 2275 |
|
| 2276 |
if has_rust_shared_deps: |
| 2277 |
args += ['-C', 'prefer-dynamic'] |
| 2278 |
if has_shared_deps or has_rust_shared_deps: |
| 2279 |
args += self.get_build_rpath_args(target, rustc) |
| 2280 |
|
| 2281 |
return deps, project_deps, args |
| 2282 |
|
| 2283 |
def generate_rust_target(self, target: build.BuildTarget, target_name: str, obj_list: T.List[str], |
| 2284 |
fortran_order_deps: T.List[File]) -> None: |
| 2285 |
orderdeps, main_rust_file = self.generate_rust_sources(target) |
| 2286 |
if main_rust_file is None: |
| 2287 |
raise RuntimeError('A Rust target has no Rust sources. This is weird. Also a bug. Please report') |
| 2288 |
|
| 2289 |
rustc = T.cast('RustCompiler', target.compilers['rust']) |
| 2290 |
args = rustc.compiler_args() |
| 2291 |
|
| 2292 |
depfile = os.path.join(self.get_target_private_dir(target), target.name + '.d') |
| 2293 |
args += self.get_rust_compiler_args(target, rustc, target.rust_crate_type, depfile) |
| 2294 |
|
| 2295 |
deps, project_deps, deps_args = self.get_rust_compiler_deps_and_args(target, rustc, obj_list) |
| 2296 |
args += deps_args |
| 2297 |
|
| 2298 |
proc_macro_dylib_path = None |
| 2299 |
if target.rust_crate_type == 'proc-macro': |
| 2300 |
proc_macro_dylib_path = self.get_target_filename_abs(target) |
| 2301 |
|
| 2302 |
self._add_rust_project_entry(target.name, |
| 2303 |
os.path.abspath(os.path.join(self.environment.build_dir, main_rust_file)), |
| 2304 |
args, target.rust_crate_type, target_name, |
| 2305 |
bool(target.subproject), |
| 2306 |
proc_macro_dylib_path, |
| 2307 |
project_deps) |
| 2308 |
|
| 2309 |
compiler_name = self.compiler_to_rule_name(rustc) |
| 2310 |
element = NinjaBuildElement(self.all_outputs, target_name, compiler_name, main_rust_file) |
| 2311 |
if orderdeps: |
| 2312 |
element.add_orderdep(orderdeps) |
| 2313 |
element.add_orderdep(self.order_deps_to_strings(target, fortran_order_deps)) |
| 2314 |
if deps: |
| 2315 |
# dependencies need to cause a relink, they're not just for ordering |
| 2316 |
element.add_dep(deps) |
| 2317 |
element.add_item('ARGS', args) |
| 2318 |
element.add_item('targetdep', depfile) |
| 2319 |
self.add_build(element) |
| 2320 |
self.create_target_source_introspection(target, rustc, args, [main_rust_file], []) |
| 2321 |
|
| 2322 |
if target.doctests: |
| 2323 |
assert target.doctests.target is not None |
| 2324 |
rustdoc = rustc.get_rustdoc() |
| 2325 |
args = rustdoc.get_exe_args() + \ |
| 2326 |
self.get_rust_compiler_args(target.doctests.target, rustdoc, target.rust_crate_type) |
| 2327 |
o, _ = self.flatten_object_list(target.doctests.target) |
| 2328 |
obj_list = unique_list(obj_list + o) |
| 2329 |
# Rustc does not add files in the obj_list to Rust rlibs, |
| 2330 |
# and is added by Meson to all of the dependencies, including here. |
| 2331 |
_, _, deps_args = self.get_rust_compiler_deps_and_args(target.doctests.target, rustdoc, obj_list) |
| 2332 |
args += deps_args |
| 2333 |
target.doctests.cmd_args = args.to_native() + [main_rust_file] + target.doctests.cmd_args |
| 2334 |
|
| 2335 |
@staticmethod |
| 2336 |
def get_rule_suffix(for_machine: MachineChoice) -> str: |
| 2337 |
return PerMachine('_FOR_BUILD', '')[for_machine] |
| 2338 |
|
| 2339 |
@classmethod |
| 2340 |
def get_compiler_rule_name(cls, lang: str, for_machine: MachineChoice, mode: str = 'COMPILER') -> str: |
| 2341 |
return f'{lang}_{mode}{cls.get_rule_suffix(for_machine)}' |
| 2342 |
|
| 2343 |
@classmethod |
| 2344 |
def compiler_to_rule_name(cls, compiler: Compiler) -> str: |
| 2345 |
return cls.get_compiler_rule_name(compiler.get_language(), compiler.for_machine, compiler.mode) |
| 2346 |
|
| 2347 |
@classmethod |
| 2348 |
def compiler_to_pch_rule_name(cls, compiler: Compiler) -> str: |
| 2349 |
return cls.get_compiler_rule_name(compiler.get_language(), compiler.for_machine, 'PCH') |
| 2350 |
|
| 2351 |
def swift_module_file_name(self, target: build.BuildTarget) -> str: |
| 2352 |
return os.path.join(self.get_target_private_dir(target), |
| 2353 |
target.swift_module_name + '.swiftmodule') |
| 2354 |
|
| 2355 |
def determine_swift_dep_modules(self, target: build.BuildTarget) -> T.List[str]: |
| 2356 |
result = [] |
| 2357 |
for l in target.link_targets: |
| 2358 |
if self.is_swift_target(l): |
| 2359 |
assert isinstance(l, build.BuildTarget) # for mypy |
| 2360 |
result.append(self.swift_module_file_name(l)) |
| 2361 |
return result |
| 2362 |
|
| 2363 |
def get_swift_link_deps(self, target: build.BuildTarget) -> T.List[str]: |
| 2364 |
result = [] |
| 2365 |
for l in target.link_targets: |
| 2366 |
result.append(self.get_target_filename(l)) |
| 2367 |
return result |
| 2368 |
|
| 2369 |
def split_swift_generated_sources(self, target: build.BuildTarget) -> T.List[str]: |
| 2370 |
all_srcs = self.get_target_generated_sources(target) |
| 2371 |
srcs: T.List[str] = [] |
| 2372 |
for i in all_srcs: |
| 2373 |
if i.endswith('.swift'): |
| 2374 |
srcs.append(i) |
| 2375 |
return srcs |
| 2376 |
|
| 2377 |
def generate_swift_target(self, target: build.BuildTarget) -> None: |
| 2378 |
module_name = target.swift_module_name |
| 2379 |
swiftc = T.cast('SwiftCompiler', target.compilers['swift']) |
| 2380 |
abssrc = [] |
| 2381 |
relsrc = [] |
| 2382 |
abs_headers = [] |
| 2383 |
header_imports = [] |
| 2384 |
|
| 2385 |
if not target.uses_swift_cpp_interop(): |
| 2386 |
cpp_targets = [t for t in target.link_targets if t.uses_swift_cpp_interop()] |
| 2387 |
if cpp_targets != []: |
| 2388 |
target_word = 'targets' if len(cpp_targets) > 1 else 'target' |
| 2389 |
first = ', '.join(repr(t.name) for t in cpp_targets[:-1]) |
| 2390 |
and_word = ' and ' if len(cpp_targets) > 1 else '' |
| 2391 |
last = repr(cpp_targets[-1].name) |
| 2392 |
enable_word = 'enable' if len(cpp_targets) > 1 else 'enables' |
| 2393 |
raise MesonException('Swift target {0} links against {1} {2}{3}{4} which {5} C++ interoperability. ' |
| 2394 |
'This requires {0} to also have it enabled. ' |
| 2395 |
'Add "swift_interoperability_mode: \'cpp\'" to the definition of {0}.' |
| 2396 |
.format(repr(target.name), target_word, first, and_word, last, enable_word)) |
| 2397 |
|
| 2398 |
for i in target.get_sources(): |
| 2399 |
if swiftc.can_compile(i): |
| 2400 |
rels = i.rel_to_builddir(self.build_to_src) |
| 2401 |
abss = os.path.normpath(os.path.join(self.environment.get_build_dir(), rels)) |
| 2402 |
relsrc.append(rels) |
| 2403 |
abssrc.append(abss) |
| 2404 |
elif compilers.is_header(i): |
| 2405 |
relh = i.rel_to_builddir(self.build_to_src) |
| 2406 |
absh = os.path.normpath(os.path.join(self.environment.get_build_dir(), relh)) |
| 2407 |
abs_headers.append(absh) |
| 2408 |
header_imports += swiftc.get_header_import_args(absh) |
| 2409 |
else: |
| 2410 |
raise InvalidArguments(f'Swift target {target.get_basename()} contains a non-swift source file.') |
| 2411 |
os.makedirs(self.get_target_private_dir_abs(target), exist_ok=True) |
| 2412 |
compile_args = self.generate_basic_compiler_args(target, swiftc) |
| 2413 |
compile_args += swiftc.get_module_args(module_name) |
| 2414 |
compile_args += swiftc.get_cxx_interoperability_args(target) |
| 2415 |
compile_args += self.build.get_project_args(swiftc, target) |
| 2416 |
compile_args += self.build.get_global_args(swiftc, target) |
| 2417 |
if isinstance(target, (build.StaticLibrary, build.SharedLibrary)): |
| 2418 |
# swiftc treats modules with a single source file, and the main.swift file in multi-source file modules |
| 2419 |
# as top-level code. This is undesirable in library targets since it emits a main function. Add the |
| 2420 |
# -parse-as-library option as necessary to prevent emitting the main function while keeping files explicitly |
| 2421 |
# named main.swift treated as the entrypoint of the module in case this is desired. |
| 2422 |
if len(abssrc) == 1 and os.path.basename(abssrc[0]) != 'main.swift': |
| 2423 |
compile_args += swiftc.get_library_args() |
| 2424 |
for i in reversed(target.get_include_dirs()): |
| 2425 |
for path in i.abs_string_list(self.source_dir, self.build_dir): |
| 2426 |
compile_args.extend(swiftc.get_include_args(path, False)) |
| 2427 |
compile_args += target.get_extra_args('swift') |
| 2428 |
link_args = swiftc.get_output_args(os.path.join(self.environment.get_build_dir(), self.get_target_filename(target))) |
| 2429 |
link_args += self.build.get_project_link_args(swiftc, target) |
| 2430 |
link_args += self.build.get_global_link_args(swiftc, target) |
| 2431 |
rundir = self.get_target_private_dir(target) |
| 2432 |
out_module_name = self.swift_module_file_name(target) |
| 2433 |
in_module_files = self.determine_swift_dep_modules(target) |
| 2434 |
abs_module_dirs = self.determine_swift_dep_dirs(target) |
| 2435 |
module_includes = [] |
| 2436 |
for x in abs_module_dirs: |
| 2437 |
module_includes += swiftc.get_include_args(x, False) |
| 2438 |
link_deps = self.get_swift_link_deps(target) |
| 2439 |
abs_link_deps = [os.path.join(self.environment.get_build_dir(), x) for x in link_deps] |
| 2440 |
for d in target.link_targets: |
| 2441 |
reldir = self.get_target_dir(d) |
| 2442 |
if reldir == '': |
| 2443 |
reldir = '.' |
| 2444 |
link_args += ['-L', os.path.normpath(os.path.join(self.environment.get_build_dir(), reldir))] |
| 2445 |
rel_generated = self.split_swift_generated_sources(target) |
| 2446 |
abs_generated = [os.path.join(self.environment.get_build_dir(), x) for x in rel_generated] |
| 2447 |
# We need absolute paths because swiftc needs to be invoked in a subdir |
| 2448 |
# and this is the easiest way about it. |
| 2449 |
objects = [] # Relative to swift invocation dir |
| 2450 |
rel_objects = [] # Relative to build.ninja |
| 2451 |
for i in abssrc + abs_generated: |
| 2452 |
base = os.path.basename(i) |
| 2453 |
oname = os.path.splitext(base)[0] + '.o' |
| 2454 |
objects.append(oname) |
| 2455 |
rel_objects.append(os.path.join(self.get_target_private_dir(target), oname)) |
| 2456 |
|
| 2457 |
rulename = self.compiler_to_rule_name(swiftc) |
| 2458 |
|
| 2459 |
# Swiftc does not seem to be able to emit objects and module files in one go. |
| 2460 |
elem = NinjaBuildElement(self.all_outputs, rel_objects, rulename, abssrc) |
| 2461 |
elem.add_dep(in_module_files + rel_generated) |
| 2462 |
elem.add_dep(abs_headers) |
| 2463 |
elem.add_item('ARGS', swiftc.get_compile_only_args() + compile_args + header_imports + abs_generated + module_includes) |
| 2464 |
elem.add_item('RUNDIR', rundir) |
| 2465 |
self.add_build(elem) |
| 2466 |
|
| 2467 |
# -g makes swiftc create a .o file with potentially the same name as one of the compile target generated ones. |
| 2468 |
mod_gen_args = [el for el in compile_args if el != '-g'] |
| 2469 |
|
| 2470 |
elem = NinjaBuildElement(self.all_outputs, out_module_name, rulename, abssrc) |
| 2471 |
elem.add_dep(in_module_files + rel_generated) |
| 2472 |
elem.add_item('ARGS', swiftc.get_mod_gen_args() + mod_gen_args + abs_generated + module_includes) |
| 2473 |
elem.add_item('RUNDIR', rundir) |
| 2474 |
self.add_build(elem) |
| 2475 |
if isinstance(target, build.StaticLibrary): |
| 2476 |
elem = self.generate_link(target, self.get_target_filename(target), |
| 2477 |
rel_objects, self.build.static_linker[target.for_machine]) |
| 2478 |
self.add_build(elem) |
| 2479 |
elif isinstance(target, build.Executable): |
| 2480 |
elem = NinjaBuildElement(self.all_outputs, self.get_target_filename(target), rulename, []) |
| 2481 |
elem.add_dep(rel_objects) |
| 2482 |
elem.add_dep(link_deps) |
| 2483 |
elem.add_item('ARGS', link_args + swiftc.get_std_exe_link_args() + objects + abs_link_deps) |
| 2484 |
elem.add_item('RUNDIR', rundir) |
| 2485 |
self.add_build(elem) |
| 2486 |
else: |
| 2487 |
raise MesonException('Swift supports only executable and static library targets.') |
| 2488 |
# Introspection information |
| 2489 |
self.create_target_source_introspection(target, swiftc, compile_args + header_imports + module_includes, relsrc, rel_generated) |
| 2490 |
|
| 2491 |
def _rsp_options(self, tool: T.Union['Compiler', 'StaticLinker']) -> NinjaRuleArgs: |
| 2492 |
"""Helper method to get rsp options. |
| 2493 |
|
| 2494 |
rsp_file_syntax() is only guaranteed to be implemented if |
| 2495 |
can_linker_accept_rsp() returns True. |
| 2496 |
""" |
| 2497 |
options: NinjaRuleArgs = {'rspable': tool.can_linker_accept_rsp()} |
| 2498 |
if options['rspable']: |
| 2499 |
options['rspfile_quote_style'] = tool.rsp_file_syntax() |
| 2500 |
return options |
| 2501 |
|
| 2502 |
def generate_static_link_rules(self) -> None: |
| 2503 |
num_pools = self.environment.coredata.optstore.get_value_for('backend_max_links') |
| 2504 |
assert isinstance(num_pools, int) |
| 2505 |
if 'java' in self.environment.coredata.compilers.host: |
| 2506 |
self.generate_java_link() |
| 2507 |
for for_machine in MachineChoice: |
| 2508 |
static_linker = self.build.static_linker[for_machine] |
| 2509 |
if static_linker is None: |
| 2510 |
continue |
| 2511 |
rule = 'STATIC_LINKER{}'.format(self.get_rule_suffix(for_machine)) |
| 2512 |
cmdlist: CommandArgs = [] |
| 2513 |
args = ['$in'] |
| 2514 |
# FIXME: Must normalize file names with pathlib.Path before writing |
| 2515 |
# them out to fix this properly on Windows. See: |
| 2516 |
# https://github.com/mesonbuild/meson/issues/1517 |
| 2517 |
# https://github.com/mesonbuild/meson/issues/1526 |
| 2518 |
if isinstance(static_linker, ArLikeLinker) and not mesonlib.is_windows(): |
| 2519 |
# `ar` has no options to overwrite archives. It always appends, |
| 2520 |
# which is never what we want. Delete an existing library first if |
| 2521 |
# it exists. https://github.com/mesonbuild/meson/issues/1355 |
| 2522 |
cmdlist = execute_wrapper + [c.format('$out') for c in rmfile_prefix] |
| 2523 |
cmdlist += static_linker.get_exelist() |
| 2524 |
cmdlist += ['$LINK_ARGS'] |
| 2525 |
cmdlist += NinjaCommandArg.list(static_linker.get_output_args('$out'), Quoting.none) |
| 2526 |
# The default ar on MacOS (at least through version 12), does not |
| 2527 |
# add extern'd variables to the symbol table by default, and |
| 2528 |
# requires that apple's ranlib be called with a special flag |
| 2529 |
# instead after linking |
| 2530 |
if static_linker.id == 'applear': |
| 2531 |
# This is a bit of a hack, but we assume that that we won't need |
| 2532 |
# an rspfile on MacOS, otherwise the arguments are passed to |
| 2533 |
# ranlib, not to ar |
| 2534 |
cmdlist.extend(args) |
| 2535 |
args = [] |
| 2536 |
# Ensure that we use the user-specified ranlib if any, and |
| 2537 |
# fallback to just picking up some ranlib otherwise |
| 2538 |
ranlib = self.environment.lookup_binary_entry(for_machine, 'ranlib') |
| 2539 |
if ranlib is None: |
| 2540 |
ranlib = ['ranlib'] |
| 2541 |
cmdlist.extend(['&&'] + ranlib + ['-c', '$out']) |
| 2542 |
description = 'Linking static target $out' |
| 2543 |
if num_pools > 0: |
| 2544 |
pool = 'pool = link_pool' |
| 2545 |
else: |
| 2546 |
pool = None |
| 2547 |
|
| 2548 |
options = self._rsp_options(static_linker) |
| 2549 |
self.add_rule(NinjaRule(rule, cmdlist, args, description, **options, extra=pool)) |
| 2550 |
|
| 2551 |
def generate_dynamic_link_rules(self) -> None: |
| 2552 |
num_pools = self.environment.coredata.optstore.get_value_for('backend_max_links') |
| 2553 |
assert isinstance(num_pools, int) |
| 2554 |
for for_machine in MachineChoice: |
| 2555 |
complist = self.environment.coredata.compilers[for_machine] |
| 2556 |
for langname, compiler in complist.items(): |
| 2557 |
if langname in {'java', 'vala', 'rust', 'cs', 'cython'}: |
| 2558 |
continue |
| 2559 |
rule = '{}_LINKER{}'.format(langname, self.get_rule_suffix(for_machine)) |
| 2560 |
command = compiler.get_linker_exelist() |
| 2561 |
args = ['$ARGS'] + NinjaCommandArg.list(compiler.get_linker_output_args('$out'), Quoting.none) + ['$in', '$LINK_ARGS'] |
| 2562 |
description = 'Linking target $out' |
| 2563 |
if num_pools > 0: |
| 2564 |
pool = 'pool = link_pool' |
| 2565 |
else: |
| 2566 |
pool = None |
| 2567 |
|
| 2568 |
options = self._rsp_options(compiler) |
| 2569 |
self.add_rule(NinjaRule(rule, command, args, description, **options, extra=pool)) |
| 2570 |
if self.environment.machines[for_machine].is_aix() and complist: |
| 2571 |
rule = 'AIX_LINKER{}'.format(self.get_rule_suffix(for_machine)) |
| 2572 |
description = 'Archiving AIX shared library' |
| 2573 |
cmdlist = compiler.get_command_to_archive_shlib() |
| 2574 |
args = [] |
| 2575 |
options = {} |
| 2576 |
self.add_rule(NinjaRule(rule, cmdlist, args, description, **options, extra=None)) |
| 2577 |
if self.environment.machines[for_machine].is_os2() and complist: |
| 2578 |
rule = 'IMPORTLIB{}'.format(self.get_rule_suffix(for_machine)) |
| 2579 |
description = 'Generating import library $out' |
| 2580 |
command = ['emximp'] |
| 2581 |
args = ['-o', '$out', '$in'] |
| 2582 |
options = {} |
| 2583 |
self.add_rule(NinjaRule(rule, command, args, description, **options, extra=None)) |
| 2584 |
|
| 2585 |
args = self.environment.get_build_command() + \ |
| 2586 |
['--internal', |
| 2587 |
'symbolextractor', |
| 2588 |
self.environment.get_build_dir(), |
| 2589 |
'$in', |
| 2590 |
'$IMPLIB', |
| 2591 |
'$out'] |
| 2592 |
symrule = 'SHSYM' |
| 2593 |
symcmd = args + ['$CROSS'] |
| 2594 |
syndesc = 'Generating symbol file $out' |
| 2595 |
self.add_rule(NinjaRule(symrule, symcmd, [], syndesc, restat=True)) |
| 2596 |
|
| 2597 |
def generate_java_compile_rule(self, compiler: Compiler) -> None: |
| 2598 |
rule = self.compiler_to_rule_name(compiler) |
| 2599 |
command = compiler.get_exelist() + ['$ARGS', '$in'] |
| 2600 |
description = 'Compiling Java sources for $FOR_JAR' |
| 2601 |
self.add_rule(NinjaRule(rule, command, [], description)) |
| 2602 |
|
| 2603 |
def generate_cs_compile_rule(self, compiler: 'CsCompiler') -> None: |
| 2604 |
rule = self.compiler_to_rule_name(compiler) |
| 2605 |
command = compiler.get_exelist() |
| 2606 |
args = ['$ARGS', '$in'] |
| 2607 |
description = 'Compiling C Sharp target $out' |
| 2608 |
self.add_rule(NinjaRule(rule, command, args, description, |
| 2609 |
rspable=mesonlib.is_windows(), |
| 2610 |
rspfile_quote_style=compiler.rsp_file_syntax())) |
| 2611 |
|
| 2612 |
def generate_vala_compile_rules(self, compiler: Compiler) -> None: |
| 2613 |
rule = self.compiler_to_rule_name(compiler) |
| 2614 |
command = compiler.get_exelist() |
| 2615 |
description = 'Compiling Vala source $in' |
| 2616 |
|
| 2617 |
depargs = compiler.get_dependency_gen_args('$out', '$DEPFILE') |
| 2618 |
depfile = '$DEPFILE' if depargs else None |
| 2619 |
depstyle = 'gcc' if depargs else None |
| 2620 |
|
| 2621 |
args = depargs + ['$ARGS', '$in'] |
| 2622 |
|
| 2623 |
self.add_rule(NinjaRule(rule, command + args, [], description, |
| 2624 |
depfile=depfile, |
| 2625 |
deps=depstyle, |
| 2626 |
restat=True)) |
| 2627 |
|
| 2628 |
def generate_cython_compile_rules(self, compiler: 'Compiler') -> None: |
| 2629 |
rule = self.compiler_to_rule_name(compiler) |
| 2630 |
description = 'Compiling Cython source $in' |
| 2631 |
command = compiler.get_exelist() |
| 2632 |
|
| 2633 |
depargs = compiler.get_dependency_gen_args('$out', '$DEPFILE') |
| 2634 |
depfile = '$out.dep' if depargs else None |
| 2635 |
|
| 2636 |
args: CommandArgs = depargs + ['$ARGS', '$in'] |
| 2637 |
args += NinjaCommandArg.list(compiler.get_output_args('$out'), Quoting.none) |
| 2638 |
self.add_rule(NinjaRule(rule, command + args, [], |
| 2639 |
description, |
| 2640 |
depfile=depfile, |
| 2641 |
restat=True)) |
| 2642 |
|
| 2643 |
def generate_rust_compile_rules(self, compiler: RustCompiler) -> None: |
| 2644 |
rule = self.compiler_to_rule_name(compiler) |
| 2645 |
command = compiler.get_exelist() + ['$ARGS', '$in'] |
| 2646 |
description = 'Compiling Rust source $in' |
| 2647 |
depfile = '$targetdep' |
| 2648 |
depstyle = 'gcc' |
| 2649 |
self.add_rule(NinjaRule(rule, command, [], description, deps=depstyle, |
| 2650 |
depfile=depfile)) |
| 2651 |
|
| 2652 |
def generate_swift_compile_rules(self, compiler: SwiftCompiler) -> None: |
| 2653 |
rule = self.compiler_to_rule_name(compiler) |
| 2654 |
wd_args = compiler.get_working_directory_args('$RUNDIR') |
| 2655 |
|
| 2656 |
if wd_args is not None: |
| 2657 |
invoc = compiler.get_exelist() + wd_args |
| 2658 |
else: |
| 2659 |
full_exe = self.environment.get_build_command() + [ |
| 2660 |
'--internal', |
| 2661 |
'dirchanger', |
| 2662 |
'$RUNDIR', |
| 2663 |
] |
| 2664 |
invoc = full_exe + compiler.get_exelist() |
| 2665 |
|
| 2666 |
command = invoc + ['$ARGS', '$in'] |
| 2667 |
description = 'Compiling Swift source $in' |
| 2668 |
self.add_rule(NinjaRule(rule, command, [], description, restat=True)) |
| 2669 |
|
| 2670 |
def use_dyndeps_for_fortran(self) -> bool: |
| 2671 |
'''Use the new Ninja feature for scanning dependencies during build, |
| 2672 |
rather than up front. Remove this and all old scanning code once Ninja |
| 2673 |
minimum version is bumped to 1.10.''' |
| 2674 |
return self.ninja_has_dyndeps |
| 2675 |
|
| 2676 |
def get_fortran_order_deps(self, deps: T.Iterable[build.BuildTarget]) -> T.List[File]: |
| 2677 |
# We don't need this order dep if we're using dyndeps, as the |
| 2678 |
# depscanner will handle this for us, which produces a better dependency |
| 2679 |
# graph |
| 2680 |
if self.use_dyndeps_for_fortran(): |
| 2681 |
return [] |
| 2682 |
|
| 2683 |
files: T.List[str] = [self.get_target_filename(t) for t in deps if t.uses_fortran()] |
| 2684 |
files.sort() |
| 2685 |
return [File(True, *os.path.split(f)) for f in files] |
| 2686 |
|
| 2687 |
def generate_fortran_dep_hack(self, crstr: str) -> None: |
| 2688 |
if self.use_dyndeps_for_fortran(): |
| 2689 |
return |
| 2690 |
rule = f'FORTRAN_DEP_HACK{crstr}' |
| 2691 |
if mesonlib.is_windows(): |
| 2692 |
cmd = ['cmd', '/C'] |
| 2693 |
else: |
| 2694 |
cmd = ['true'] |
| 2695 |
self.add_rule_comment(NinjaComment('''Workaround for these issues: |
| 2696 |
https://groups.google.com/forum/#!topic/ninja-build/j-2RfBIOd_8 |
| 2697 |
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47485''')) |
| 2698 |
self.add_rule(NinjaRule(rule, cmd, [], 'Dep hack', restat=True)) |
| 2699 |
|
| 2700 |
def generate_llvm_ir_compile_rule(self, compiler: Compiler) -> None: |
| 2701 |
if self.created_llvm_ir_rule[compiler.for_machine]: |
| 2702 |
return |
| 2703 |
rule = self.get_compiler_rule_name('llvm_ir', compiler.for_machine) |
| 2704 |
command = compiler.get_exelist() |
| 2705 |
args = ['$ARGS'] + NinjaCommandArg.list(compiler.get_output_args('$out'), Quoting.none) + compiler.get_compile_only_args() + ['$in'] |
| 2706 |
description = 'Compiling LLVM IR object $in' |
| 2707 |
|
| 2708 |
options = self._rsp_options(compiler) |
| 2709 |
|
| 2710 |
self.add_rule(NinjaRule(rule, command, args, description, **options)) |
| 2711 |
self.created_llvm_ir_rule[compiler.for_machine] = True |
| 2712 |
|
| 2713 |
def generate_tasking_mil_compile_rules(self, compiler: Compiler) -> None: |
| 2714 |
rule = self.get_compiler_rule_name('tasking_mil_compile', compiler.for_machine) |
| 2715 |
depargs = NinjaCommandArg.list(compiler.get_dependency_gen_args('$out', '$DEPFILE'), Quoting.none) |
| 2716 |
command = compiler.get_exelist() |
| 2717 |
args = ['$ARGS'] + depargs + NinjaCommandArg.list(compiler.get_output_args('$out'), Quoting.none) + ['-cm', '$in'] |
| 2718 |
description = 'Compiling to C object $in' |
| 2719 |
if compiler.get_depfile_format() == 'msvc': |
| 2720 |
deps = 'msvc' |
| 2721 |
depfile = None |
| 2722 |
else: |
| 2723 |
deps = 'gcc' |
| 2724 |
depfile = '$DEPFILE' |
| 2725 |
|
| 2726 |
options = self._rsp_options(compiler) |
| 2727 |
|
| 2728 |
self.add_rule(NinjaRule(rule, command, args, description, **options, deps=deps, depfile=depfile)) |
| 2729 |
|
| 2730 |
def generate_tasking_mil_link_rules(self, compiler: Compiler) -> None: |
| 2731 |
rule = self.get_compiler_rule_name('tasking_mil_link', compiler.for_machine) |
| 2732 |
command = compiler.get_exelist() |
| 2733 |
args = ['$ARGS', '--mil-link'] + NinjaCommandArg.list(compiler.get_output_args('$out'), Quoting.none) + ['-c', '$in'] |
| 2734 |
description = 'MIL linking object $out' |
| 2735 |
|
| 2736 |
options = self._rsp_options(compiler) |
| 2737 |
|
| 2738 |
self.add_rule(NinjaRule(rule, command, args, description, **options)) |
| 2739 |
|
| 2740 |
def generate_compile_rule_for(self, langname: str, compiler: Compiler) -> None: |
| 2741 |
if langname == 'java': |
| 2742 |
self.generate_java_compile_rule(compiler) |
| 2743 |
return |
| 2744 |
if langname == 'cs': |
| 2745 |
if self.environment.machines.matches_build_machine(compiler.for_machine): |
| 2746 |
self.generate_cs_compile_rule(T.cast('CsCompiler', compiler)) |
| 2747 |
return |
| 2748 |
if langname == 'vala': |
| 2749 |
self.generate_vala_compile_rules(compiler) |
| 2750 |
return |
| 2751 |
if langname == 'rust': |
| 2752 |
self.generate_rust_compile_rules(T.cast('RustCompiler', compiler)) |
| 2753 |
return |
| 2754 |
if langname == 'swift': |
| 2755 |
if self.environment.machines.matches_build_machine(compiler.for_machine): |
| 2756 |
self.generate_swift_compile_rules(T.cast('SwiftCompiler', compiler)) |
| 2757 |
return |
| 2758 |
if langname == 'cython': |
| 2759 |
self.generate_cython_compile_rules(compiler) |
| 2760 |
return |
| 2761 |
crstr = self.get_rule_suffix(compiler.for_machine) |
| 2762 |
options = self._rsp_options(compiler) |
| 2763 |
restat = False |
| 2764 |
if langname == 'fortran': |
| 2765 |
self.generate_fortran_dep_hack(crstr) |
| 2766 |
# gfortran does not update the modification time of *.mod files, therefore restat is needed. |
| 2767 |
# See also: https://github.com/ninja-build/ninja/pull/2275 |
| 2768 |
restat = True |
| 2769 |
rule = self.compiler_to_rule_name(compiler) |
| 2770 |
if langname == 'cuda': |
| 2771 |
# for cuda, we manually escape target name ($out) as $CUDA_ESCAPED_TARGET because nvcc doesn't support `-MQ` flag |
| 2772 |
depargs = NinjaCommandArg.list(compiler.get_dependency_gen_args('$CUDA_ESCAPED_TARGET', '$DEPFILE'), Quoting.none) |
| 2773 |
else: |
| 2774 |
depargs = NinjaCommandArg.list(compiler.get_dependency_gen_args('$out', '$DEPFILE'), Quoting.none) |
| 2775 |
command = compiler.get_exelist() |
| 2776 |
args = ['$ARGS'] + depargs + NinjaCommandArg.list(compiler.get_output_args('$out'), Quoting.none) + compiler.get_compile_only_args() + ['$in'] |
| 2777 |
description = f'Compiling {compiler.get_display_language()} object $out' |
| 2778 |
if compiler.get_depfile_format() == 'msvc': |
| 2779 |
deps = 'msvc' |
| 2780 |
depfile = None |
| 2781 |
else: |
| 2782 |
deps = 'gcc' |
| 2783 |
depfile = '$DEPFILE' |
| 2784 |
self.add_rule(NinjaRule(rule, command, args, description, **options, |
| 2785 |
deps=deps, depfile=depfile, restat=restat)) |
| 2786 |
|
| 2787 |
def generate_pch_rule_for(self, langname: str, compiler: Compiler) -> None: |
| 2788 |
if langname not in {'c', 'cpp'}: |
| 2789 |
return |
| 2790 |
rule = self.compiler_to_pch_rule_name(compiler) |
| 2791 |
depargs = compiler.get_dependency_gen_args('$out', '$DEPFILE') |
| 2792 |
|
| 2793 |
if compiler.get_argument_syntax() == 'msvc': |
| 2794 |
output = [] |
| 2795 |
else: |
| 2796 |
output = NinjaCommandArg.list(compiler.get_output_args('$out'), Quoting.none) |
| 2797 |
|
| 2798 |
if 'mwcc' in compiler.id: |
| 2799 |
output[0].s = '-precompile' |
| 2800 |
command = compiler.get_exelist() + ['$ARGS'] + depargs + output + ['$in'] # '-c' must be removed |
| 2801 |
else: |
| 2802 |
command = compiler.get_exelist() + ['$ARGS'] + depargs + output + compiler.get_compile_only_args() + ['$in'] |
| 2803 |
description = 'Precompiling header $in' |
| 2804 |
if compiler.get_depfile_format() == 'msvc': |
| 2805 |
deps = 'msvc' |
| 2806 |
depfile = None |
| 2807 |
else: |
| 2808 |
deps = 'gcc' |
| 2809 |
depfile = '$DEPFILE' |
| 2810 |
self.add_rule(NinjaRule(rule, command, [], description, deps=deps, |
| 2811 |
depfile=depfile)) |
| 2812 |
|
| 2813 |
def generate_scanner_rules(self) -> None: |
| 2814 |
rulename = 'depscan' |
| 2815 |
if self.ninja.has_rule(rulename): |
| 2816 |
# Scanning command is the same for native and cross compilation. |
| 2817 |
return |
| 2818 |
|
| 2819 |
command = self.environment.get_build_command() + \ |
| 2820 |
['--internal', 'depscan'] |
| 2821 |
args = ['$picklefile', '$out', '$in'] |
| 2822 |
description = 'Scanning target $name for modules' |
| 2823 |
rule = NinjaRule(rulename, command, args, description) |
| 2824 |
self.add_rule(rule) |
| 2825 |
|
| 2826 |
rulename = 'depaccumulate' |
| 2827 |
command = self.environment.get_build_command() + \ |
| 2828 |
['--internal', 'depaccumulate'] |
| 2829 |
args = ['$out', '$in'] |
| 2830 |
description = 'Generating dynamic dependency information for target $name' |
| 2831 |
rule = NinjaRule(rulename, command, args, description) |
| 2832 |
self.add_rule(rule) |
| 2833 |
|
| 2834 |
def generate_compile_rules(self) -> None: |
| 2835 |
for for_machine in MachineChoice: |
| 2836 |
clist = self.environment.coredata.compilers[for_machine] |
| 2837 |
for langname, compiler in clist.items(): |
| 2838 |
if compiler.get_id() == 'clang': |
| 2839 |
self.generate_llvm_ir_compile_rule(compiler) |
| 2840 |
if compiler.get_id() == 'tasking': |
| 2841 |
self.generate_tasking_mil_compile_rules(compiler) |
| 2842 |
self.generate_compile_rule_for(langname, compiler) |
| 2843 |
self.generate_pch_rule_for(langname, compiler) |
| 2844 |
for mode in compiler.get_modes(): |
| 2845 |
self.generate_compile_rule_for(langname, mode) |
| 2846 |
|
| 2847 |
def generate_generator_list_rules(self, target: build.BuildTarget) -> None: |
| 2848 |
# CustomTargets have already written their rules and |
| 2849 |
# CustomTargetIndexes don't actually get generated, so write rules for |
| 2850 |
# GeneratedLists here |
| 2851 |
for genlist in target.get_generated_sources(): |
| 2852 |
if isinstance(genlist, (build.CustomTarget, build.CustomTargetIndex)): |
| 2853 |
continue |
| 2854 |
self.generate_genlist_for_target(genlist, target) |
| 2855 |
|
| 2856 |
def replace_paths(self, target: build.BuildTarget | build.CustomTarget, args: T.List[str], override_subdir: T.Optional[str] = None) -> T.List[str]: |
| 2857 |
if override_subdir: |
| 2858 |
source_target_dir = os.path.join(self.build_to_src, override_subdir) |
| 2859 |
else: |
| 2860 |
source_target_dir = self.get_target_source_dir(target) |
| 2861 |
relout = self.get_target_private_dir(target) |
| 2862 |
args = [x.replace("@SOURCE_DIR@", self.build_to_src).replace("@BUILD_DIR@", relout) |
| 2863 |
for x in args] |
| 2864 |
args = [x.replace("@CURRENT_SOURCE_DIR@", source_target_dir) for x in args] |
| 2865 |
args = [x.replace("@SOURCE_ROOT@", self.build_to_src).replace("@BUILD_ROOT@", '.') |
| 2866 |
for x in args] |
| 2867 |
args = [x.replace('\\', '/') for x in args] |
| 2868 |
return args |
| 2869 |
|
| 2870 |
def generate_genlist_for_target(self, genlist: build.GeneratedList, target: build.BuildTarget | build.CustomTarget) -> None: |
| 2871 |
for x in genlist.depends: |
| 2872 |
if isinstance(x, build.GeneratedList): |
| 2873 |
self.generate_genlist_for_target(x, target) |
| 2874 |
generator = genlist.get_generator() |
| 2875 |
subdir = genlist.subdir |
| 2876 |
exe = generator.get_exe() |
| 2877 |
infilelist = genlist.get_inputs() |
| 2878 |
dependencies = self.get_target_depend_files(genlist) |
| 2879 |
dependencies += self.get_paths_for_dep_outputs(target, generator.depends) |
| 2880 |
dependencies += self.get_paths_for_dep_outputs(target, genlist.extra_depends) |
| 2881 |
for curfile in infilelist: |
| 2882 |
infilename = curfile.rel_to_builddir(self.build_to_src, self.get_target_private_dir(target)) |
| 2883 |
base_args = generator.get_arglist(infilename) |
| 2884 |
outfiles = genlist.get_outputs_for(curfile) |
| 2885 |
outfilespriv = [os.path.join(self.get_target_private_dir(target), of) for of in outfiles] |
| 2886 |
|
| 2887 |
if len(generator.outputs) == 1: |
| 2888 |
sole_output = outfilespriv[0] |
| 2889 |
else: |
| 2890 |
sole_output = f'{curfile}' |
| 2891 |
|
| 2892 |
if generator.depfile is None: |
| 2893 |
rulename = 'CUSTOM_COMMAND' |
| 2894 |
args = base_args |
| 2895 |
else: |
| 2896 |
rulename = 'CUSTOM_COMMAND_DEP' |
| 2897 |
depfilename = generator.get_dep_outname(infilename) |
| 2898 |
if genlist.preserve_path_from: |
| 2899 |
path_segment = genlist.get_preserved_path_segment(curfile) |
| 2900 |
depfilename = os.path.join(path_segment, depfilename) |
| 2901 |
depfile = os.path.join(self.get_target_private_dir(target), depfilename) |
| 2902 |
args = [x.replace('@DEPFILE@', depfile) for x in base_args] |
| 2903 |
args = [x.replace("@INPUT@", infilename).replace('@OUTPUT@', sole_output) |
| 2904 |
for x in args] |
| 2905 |
args = self.replace_outputs(args, self.get_target_private_dir(target), outfiles) |
| 2906 |
args = self.replace_paths(target, args, override_subdir=subdir) |
| 2907 |
cmdlist, reason = self.as_meson_exe_cmdline(exe, |
| 2908 |
self.replace_extra_args(args, genlist), |
| 2909 |
capture=outfilespriv[0] if generator.capture else None, |
| 2910 |
env=genlist.env) |
| 2911 |
abs_pdir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target)) |
| 2912 |
os.makedirs(abs_pdir, exist_ok=True) |
| 2913 |
|
| 2914 |
elem = NinjaBuildElement(self.all_outputs, outfilespriv, rulename, infilename) |
| 2915 |
elem.add_dep(dependencies) |
| 2916 |
if generator.depfile is not None: |
| 2917 |
elem.add_item('DEPFILE', depfile) |
| 2918 |
|
| 2919 |
if len(generator.outputs) == 1: |
| 2920 |
what = f'{sole_output!r}' |
| 2921 |
else: |
| 2922 |
# since there are multiple outputs, we log the source that caused the rebuild |
| 2923 |
what = f'from {sole_output!r}' |
| 2924 |
if reason: |
| 2925 |
reason = f' (wrapped by meson {reason})' |
| 2926 |
elem.add_item('DESC', f'Generating {what}{reason}') |
| 2927 |
|
| 2928 |
elem.add_item('COMMAND', cmdlist) |
| 2929 |
self.add_build(elem) |
| 2930 |
|
| 2931 |
def scan_fortran_module_outputs(self, target: build.BuildTarget) -> None: |
| 2932 |
""" |
| 2933 |
Find all module and submodule made available in a Fortran code file. |
| 2934 |
""" |
| 2935 |
if self.use_dyndeps_for_fortran(): |
| 2936 |
return |
| 2937 |
compiler = None |
| 2938 |
# TODO other compilers |
| 2939 |
for lang, c in self.environment.coredata.compilers.host.items(): |
| 2940 |
if lang == 'fortran': |
| 2941 |
compiler = c |
| 2942 |
break |
| 2943 |
if compiler is None: |
| 2944 |
self.fortran_deps[target.get_basename()] = {} |
| 2945 |
return |
| 2946 |
|
| 2947 |
modre = re.compile(FORTRAN_MODULE_PAT, re.IGNORECASE) |
| 2948 |
submodre = re.compile(FORTRAN_SUBMOD_PAT, re.IGNORECASE) |
| 2949 |
module_files: T.Dict[str, File] = {} |
| 2950 |
submodule_files: T.Dict[str, File] = {} |
| 2951 |
for s in target.get_sources(): |
| 2952 |
# FIXME, does not work for Fortran sources generated by |
| 2953 |
# custom_target() and generator() as those are run after |
| 2954 |
# the configuration (configure_file() is OK) |
| 2955 |
if not compiler.can_compile(s): |
| 2956 |
continue |
| 2957 |
filename = s.absolute_path(self.environment.get_source_dir(), |
| 2958 |
self.environment.get_build_dir()) |
| 2959 |
# Fortran keywords must be ASCII. |
| 2960 |
with open(filename, encoding='ascii', errors='ignore') as f: |
| 2961 |
for line in f: |
| 2962 |
modmatch = modre.match(line) |
| 2963 |
if modmatch is not None: |
| 2964 |
modname = modmatch.group(1).lower() |
| 2965 |
if modname in module_files: |
| 2966 |
raise InvalidArguments( |
| 2967 |
f'Namespace collision: module {modname} defined in ' |
| 2968 |
f'two files {module_files[modname]} and {s}.') |
| 2969 |
module_files[modname] = s |
| 2970 |
else: |
| 2971 |
submodmatch = submodre.match(line) |
| 2972 |
if submodmatch is not None: |
| 2973 |
# '_' is arbitrarily used to distinguish submod from mod. |
| 2974 |
parents = submodmatch.group(1).lower().split(':') |
| 2975 |
submodname = parents[0] + '_' + submodmatch.group(2).lower() |
| 2976 |
|
| 2977 |
if submodname in submodule_files: |
| 2978 |
raise InvalidArguments( |
| 2979 |
f'Namespace collision: submodule {submodname} defined in ' |
| 2980 |
f'two files {submodule_files[submodname]} and {s}.') |
| 2981 |
submodule_files[submodname] = s |
| 2982 |
|
| 2983 |
self.fortran_deps[target.get_basename()] = {**module_files, **submodule_files} |
| 2984 |
|
| 2985 |
def get_fortran_deps(self, compiler: FortranCompiler, src: Path, target: build.BuildTarget) -> T.List[str]: |
| 2986 |
""" |
| 2987 |
Find all module and submodule needed by a Fortran target |
| 2988 |
""" |
| 2989 |
if self.use_dyndeps_for_fortran(): |
| 2990 |
return [] |
| 2991 |
|
| 2992 |
dirname = Path(self.get_target_private_dir(target)) |
| 2993 |
tdeps = self.fortran_deps[target.get_basename()] |
| 2994 |
srcdir = Path(self.source_dir) |
| 2995 |
|
| 2996 |
mod_files = _scan_fortran_file_deps(src, srcdir, dirname, tdeps, compiler) |
| 2997 |
return mod_files |
| 2998 |
|
| 2999 |
def get_no_stdlib_link_args(self, target: build.BuildTarget, linker: Compiler | StaticLinker) -> T.List[str]: |
| 3000 |
if hasattr(linker, 'language') and linker.language in self.build.stdlibs[target.for_machine]: |
| 3001 |
return linker.get_no_stdlib_link_args() |
| 3002 |
return [] |
| 3003 |
|
| 3004 |
def get_compile_debugfile_args(self, compiler: Compiler, target: build.BuildTarget, objfile: str) -> T.List[str]: |
| 3005 |
# The way MSVC uses PDB files is documented exactly nowhere so |
| 3006 |
# the following is what we have been able to decipher via |
| 3007 |
# reverse engineering. |
| 3008 |
# |
| 3009 |
# Each object file gets the path of its PDB file written |
| 3010 |
# inside it. This can be either the final PDB (for, say, |
| 3011 |
# foo.exe) or an object pdb (for foo.obj). If the former, then |
| 3012 |
# each compilation step locks the pdb file for writing, which |
| 3013 |
# is a bottleneck and object files from one target cannot be |
| 3014 |
# used in a different target. The latter seems to be the |
| 3015 |
# sensible one (and what Unix does) but there is a catch. If |
| 3016 |
# you try to use precompiled headers MSVC will error out |
| 3017 |
# because both source and pch pdbs go in the same file and |
| 3018 |
# they must be the same. |
| 3019 |
# |
| 3020 |
# This means: |
| 3021 |
# |
| 3022 |
# - pch files must be compiled anew for every object file (negating |
| 3023 |
# the entire point of having them in the first place) |
| 3024 |
# - when using pch, output must go to the target pdb |
| 3025 |
# |
| 3026 |
# Since both of these are broken in some way, use the one that |
| 3027 |
# works for each target. This unfortunately means that you |
| 3028 |
# can't combine pch and object extraction in a single target. |
| 3029 |
# |
| 3030 |
# PDB files also lead to filename collisions. A target foo.exe |
| 3031 |
# has a corresponding foo.pdb. A shared library foo.dll _also_ |
| 3032 |
# has pdb file called foo.pdb. So will a static library |
| 3033 |
# foo.lib, which clobbers both foo.pdb _and_ the dll file's |
| 3034 |
# export library called foo.lib (by default, currently we name |
| 3035 |
# them libfoo.a to avoid this issue). You can give the files |
| 3036 |
# unique names such as foo_exe.pdb but VC also generates a |
| 3037 |
# bunch of other files which take their names from the target |
| 3038 |
# basename (i.e. "foo") and stomp on each other. |
| 3039 |
# |
| 3040 |
# CMake solves this problem by doing two things. First of all |
| 3041 |
# static libraries do not generate pdb files at |
| 3042 |
# all. Presumably you don't need them and VC is smart enough |
| 3043 |
# to look up the original data when linking (speculation, not |
| 3044 |
# tested). The second solution is that you can only have |
| 3045 |
# target named "foo" as an exe, shared lib _or_ static |
| 3046 |
# lib. This makes filename collisions not happen. The downside |
| 3047 |
# is that you can't have an executable foo that uses a shared |
| 3048 |
# library libfoo.so, which is a common idiom on Unix. |
| 3049 |
# |
| 3050 |
# If you feel that the above is completely wrong and all of |
| 3051 |
# this is actually doable, please send patches. |
| 3052 |
|
| 3053 |
if target.has_pch(): |
| 3054 |
tfilename = self.get_target_debug_filename_abs(target) |
| 3055 |
if not tfilename: |
| 3056 |
tfilename = self.get_target_filename_abs(target) |
| 3057 |
return compiler.get_compile_debugfile_args(tfilename, pch=True) |
| 3058 |
else: |
| 3059 |
return compiler.get_compile_debugfile_args(objfile, pch=False) |
| 3060 |
|
| 3061 |
def get_link_debugfile_name(self, linker: T.Union[Compiler, StaticLinker], target: build.BuildTarget) -> T.Optional[str]: |
| 3062 |
filename = self.get_target_debug_filename(target) |
| 3063 |
if filename: |
| 3064 |
return linker.get_link_debugfile_name(filename) |
| 3065 |
return None |
| 3066 |
|
| 3067 |
def get_link_debugfile_args(self, linker: T.Union[Compiler, StaticLinker], target: build.BuildTarget) -> T.List[str]: |
| 3068 |
filename = self.get_target_debug_filename(target) |
| 3069 |
if filename: |
| 3070 |
return linker.get_link_debugfile_args(filename) |
| 3071 |
return [] |
| 3072 |
|
| 3073 |
def generate_llvm_ir_compile(self, target: build.BuildTarget, src: FileOrString) -> T.Tuple[str, str]: |
| 3074 |
compiler = get_compiler_for_source(target.compilers.values(), src) |
| 3075 |
commands = compiler.compiler_args() |
| 3076 |
# Compiler args for compiling this target |
| 3077 |
commands += compilers.get_base_compile_args(target, compiler, self.environment) |
| 3078 |
if isinstance(src, File): |
| 3079 |
if src.is_built: |
| 3080 |
src_filename = os.path.join(src.subdir, src.fname) |
| 3081 |
else: |
| 3082 |
src_filename = src.fname |
| 3083 |
elif os.path.isabs(src): |
| 3084 |
src_filename = os.path.basename(src) |
| 3085 |
else: |
| 3086 |
src_filename = src |
| 3087 |
obj_basename = self.canonicalize_filename(src_filename) |
| 3088 |
rel_obj = os.path.join(self.get_target_private_dir(target), obj_basename) |
| 3089 |
rel_obj += '.' + self.environment.machines[target.for_machine].get_object_suffix() |
| 3090 |
commands += self.get_compile_debugfile_args(compiler, target, rel_obj) |
| 3091 |
if isinstance(src, File): |
| 3092 |
if src.is_built: |
| 3093 |
rel_src = src.fname |
| 3094 |
else: |
| 3095 |
rel_src = src.rel_to_builddir(self.build_to_src) |
| 3096 |
else: |
| 3097 |
raise InvalidArguments(f'Invalid source type: {src!r}') |
| 3098 |
# Write the Ninja build command |
| 3099 |
compiler_name = self.get_compiler_rule_name('llvm_ir', compiler.for_machine) |
| 3100 |
element = NinjaBuildElement(self.all_outputs, rel_obj, compiler_name, rel_src) |
| 3101 |
element.add_item('ARGS', commands) |
| 3102 |
self.add_build(element) |
| 3103 |
return (rel_obj, rel_src) |
| 3104 |
|
| 3105 |
@lru_cache(maxsize=None) |
| 3106 |
def generate_inc_dir(self, compiler: 'Compiler', d: str, basedir: str, is_system: bool |
| 3107 |
) -> T.Tuple[ImmutableListProtocol[str], ImmutableListProtocol[str]]: |
| 3108 |
expdir = os.path.normpath(os.path.join(basedir, d)) |
| 3109 |
srctreedir = os.path.normpath(os.path.join(self.build_to_src, expdir)) |
| 3110 |
sargs = compiler.get_include_args(srctreedir, is_system) |
| 3111 |
# There may be include dirs where a build directory has not been |
| 3112 |
# created for some source dir. For example if someone does this: |
| 3113 |
# |
| 3114 |
# inc = include_directories('foo/bar/baz') |
| 3115 |
# |
| 3116 |
# But never subdir()s into the actual dir. |
| 3117 |
if os.path.isdir(os.path.join(self.environment.get_build_dir(), expdir)): |
| 3118 |
bargs = compiler.get_include_args(expdir, is_system) |
| 3119 |
else: |
| 3120 |
bargs = [] |
| 3121 |
return (sargs, bargs) |
| 3122 |
|
| 3123 |
def _generate_single_compile(self, target: build.BuildTarget, compiler: Compiler) -> CompilerArgs: |
| 3124 |
commands = target.get_single_compile_base_args(compiler) |
| 3125 |
commands += self._generate_single_compile_target_args(target, compiler) |
| 3126 |
return commands |
| 3127 |
|
| 3128 |
@lru_cache(maxsize=None) |
| 3129 |
def _generate_single_compile_target_args(self, target: build.BuildTarget, compiler: Compiler) -> ImmutableListProtocol[str]: |
| 3130 |
# Add compiler args and include paths from several sources; defaults, |
| 3131 |
# build options, external dependencies, etc. |
| 3132 |
commands = self.generate_basic_compiler_args(target, compiler) |
| 3133 |
commands += compiler.get_show_dep_args() |
| 3134 |
# Add custom target dirs as includes automatically, but before |
| 3135 |
# target-specific include directories. |
| 3136 |
if target.implicit_include_directories: |
| 3137 |
commands += self.get_custom_target_dir_include_args(target, compiler) |
| 3138 |
# Add include dirs from the `include_directories:` kwarg on the target |
| 3139 |
# and from `include_directories:` of internal deps of the target. |
| 3140 |
# |
| 3141 |
# Target include dirs should override internal deps include dirs. |
| 3142 |
# This is handled in BuildTarget.process_kwargs() |
| 3143 |
# |
| 3144 |
# Include dirs from internal deps should override include dirs from |
| 3145 |
# external deps and must maintain the order in which they are specified. |
| 3146 |
# Hence, we must reverse the list so that the order is preserved. |
| 3147 |
for i in reversed(target.get_include_dirs()): |
| 3148 |
basedir = i.curdir |
| 3149 |
# Each directory must be added to CompilerArgs individually |
| 3150 |
# via a separate ``commands +=`` call, in reversed order. |
| 3151 |
# |
| 3152 |
# CompilerArgs.__iadd__ prepends ``-I`` args (which are in |
| 3153 |
# CLikeCompilerArgs.prepend_prefixes) but appends ``-isystem`` |
| 3154 |
# args (which are not). When adding one directory at a time |
| 3155 |
# in reversed order, this produces the correct result for |
| 3156 |
# both flag types: |
| 3157 |
# |
| 3158 |
# - For ``-I`` (prepended): each flag is inserted at the |
| 3159 |
# front, so reversed iteration produces the original |
| 3160 |
# order — first-listed directory appears first on the |
| 3161 |
# command line and is searched first. |
| 3162 |
# |
| 3163 |
# - For ``-isystem`` (appended): each flag is added at the |
| 3164 |
# back, so reversed iteration produces a reversed sequence |
| 3165 |
# on the command line — *last*-listed directory appears |
| 3166 |
# first and is searched first. |
| 3167 |
# |
| 3168 |
# Adding all directories in a single ``commands +=`` call |
| 3169 |
# would break ``-isystem`` ordering: the whole list would be |
| 3170 |
# appended at once in the original (unreversed) order, making |
| 3171 |
# the *first*-listed directory appear first instead of last. |
| 3172 |
for d in reversed(i.incdirs): |
| 3173 |
sargs, bargs = self.generate_inc_dir(compiler, d, basedir, i.is_system) |
| 3174 |
commands += sargs |
| 3175 |
commands += bargs |
| 3176 |
for d in i.extra_build_dirs: |
| 3177 |
commands += compiler.get_include_args(d, i.is_system) |
| 3178 |
# Add per-target compile args, f.ex, `c_args : ['-DFOO']`. We set these |
| 3179 |
# near the end since these are supposed to override everything else. |
| 3180 |
commands += self.escape_extra_args(target.get_extra_args(compiler.get_language())) |
| 3181 |
|
| 3182 |
# D specific additional flags |
| 3183 |
if compiler.language == 'd': |
| 3184 |
commands += compiler.get_feature_args(target.d_features, self.build_to_src) |
| 3185 |
|
| 3186 |
# Add source dir and build dir. Project-specific and target-specific |
| 3187 |
# include paths must override per-target compile args, include paths |
| 3188 |
# from external dependencies, internal dependencies, and from |
| 3189 |
# per-target `include_directories:` |
| 3190 |
# |
| 3191 |
# We prefer headers in the build dir over the source dir since, for |
| 3192 |
# instance, the user might have an srcdir == builddir Autotools build |
| 3193 |
# in their source tree. Many projects that are moving to Meson have |
| 3194 |
# both Meson and Autotools in parallel as part of the transition. |
| 3195 |
if target.implicit_include_directories: |
| 3196 |
commands += self.get_source_dir_include_args(target, compiler) |
| 3197 |
if target.implicit_include_directories: |
| 3198 |
commands += self.get_build_dir_include_args(target, compiler) |
| 3199 |
# Finally add the private dir for the target to the include path. This |
| 3200 |
# must override everything else and must be the final path added. |
| 3201 |
commands += compiler.get_include_args(self.get_target_private_dir(target), False) |
| 3202 |
return list(commands) |
| 3203 |
|
| 3204 |
# Returns a dictionary, mapping from each compiler src type (e.g. 'c', 'cpp', etc.) to a list of compiler arg strings |
| 3205 |
# used for that respective src type. |
| 3206 |
# Currently used for the purpose of populating VisualStudio intellisense fields but possibly useful in other scenarios. |
| 3207 |
def generate_common_compile_args_per_src_type(self, target: build.BuildTarget) -> T.Dict[Language, T.List[str]]: |
| 3208 |
src_type_to_args = {} |
| 3209 |
|
| 3210 |
use_pch = self.target_uses_pch(target) |
| 3211 |
|
| 3212 |
for src_type_str in target.compilers: |
| 3213 |
compiler = target.compilers[src_type_str] |
| 3214 |
commands = target.get_single_compile_base_args(compiler) |
| 3215 |
|
| 3216 |
# Include PCH header as first thing as it must be the first one or it will be |
| 3217 |
# ignored by gcc https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100462 |
| 3218 |
if use_pch and 'mw' not in compiler.id: |
| 3219 |
commands += self.get_pch_include_args(compiler, target) |
| 3220 |
|
| 3221 |
commands += self._generate_single_compile_target_args(target, compiler) |
| 3222 |
|
| 3223 |
# Metrowerks compilers require PCH include args to come after intraprocedural analysis args |
| 3224 |
if use_pch and 'mw' in compiler.id: |
| 3225 |
commands += self.get_pch_include_args(compiler, target) |
| 3226 |
|
| 3227 |
commands = commands.compiler.compiler_args(commands) |
| 3228 |
|
| 3229 |
src_type_to_args[src_type_str] = commands.to_native() |
| 3230 |
return src_type_to_args |
| 3231 |
|
| 3232 |
def order_deps_to_strings(self, target: build.BuildTarget, order_deps: T.List[File] | T.List[FileOrString]) -> T.List[str]: |
| 3233 |
result: T.List[str] = [] |
| 3234 |
for d in order_deps: |
| 3235 |
if isinstance(d, File): |
| 3236 |
d = d.rel_to_builddir(self.build_to_src) |
| 3237 |
elif not self.has_dir_part(d): |
| 3238 |
d = os.path.join(self.get_target_private_dir(target), d) |
| 3239 |
result.append(d) |
| 3240 |
return result |
| 3241 |
|
| 3242 |
def generate_single_compile(self, target: build.BuildTarget, src: FileOrString, |
| 3243 |
is_generated: bool = False, |
| 3244 |
header_deps: T.Optional[T.List[FileOrString]] = None, |
| 3245 |
order_deps: T.Optional[T.List[File] | T.List[FileOrString]] = None, |
| 3246 |
extra_args: T.Optional[T.List[str]] = None, |
| 3247 |
unity_sources: list[File] | None = None, |
| 3248 |
) -> T.Tuple[str, str]: |
| 3249 |
""" |
| 3250 |
Compiles C/C++, ObjC/ObjC++, Fortran, and D sources |
| 3251 |
""" |
| 3252 |
header_deps = header_deps if header_deps is not None else [] |
| 3253 |
order_deps = order_deps if order_deps is not None else [] |
| 3254 |
|
| 3255 |
if isinstance(src, str) and src.endswith('.h'): |
| 3256 |
raise AssertionError(f'BUG: sources should not contain headers {src!r}') |
| 3257 |
|
| 3258 |
compiler = get_compiler_for_source(target.compilers.values(), src) |
| 3259 |
commands = target.get_single_compile_base_args(compiler) |
| 3260 |
|
| 3261 |
# Include PCH header as first thing as it must be the first one or it will be |
| 3262 |
# ignored by gcc https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100462 |
| 3263 |
use_pch = self.target_uses_pch(target) |
| 3264 |
if use_pch and 'mw' not in compiler.id: |
| 3265 |
commands += self.get_pch_include_args(compiler, target) |
| 3266 |
|
| 3267 |
commands += self._generate_single_compile_target_args(target, compiler) |
| 3268 |
|
| 3269 |
# Metrowerks compilers require PCH include args to come after intraprocedural analysis args |
| 3270 |
if use_pch and 'mw' in compiler.id: |
| 3271 |
commands += self.get_pch_include_args(compiler, target) |
| 3272 |
|
| 3273 |
commands = commands.compiler.compiler_args(commands) |
| 3274 |
|
| 3275 |
# Create introspection information |
| 3276 |
if is_generated is False: |
| 3277 |
self.create_target_source_introspection(target, compiler, commands, [src], [], unity_sources) |
| 3278 |
else: |
| 3279 |
self.create_target_source_introspection(target, compiler, commands, [], [src], unity_sources) |
| 3280 |
|
| 3281 |
build_dir = self.environment.get_build_dir() |
| 3282 |
if isinstance(src, File): |
| 3283 |
if src.is_built and path_has_root(src.fname): |
| 3284 |
raise MesonBugException('absolute file name for built file ' + src.relative_name()) |
| 3285 |
rel_src = src.rel_to_builddir(self.build_to_src) |
| 3286 |
elif is_generated: |
| 3287 |
raise AssertionError(f'BUG: broken generated source file handling for {src!r}') |
| 3288 |
else: |
| 3289 |
raise InvalidArguments(f'Invalid source type: {src!r}') |
| 3290 |
obj_basename = self.object_filename_from_source(target, compiler, src) |
| 3291 |
rel_obj = os.path.join(self.get_target_private_dir(target), obj_basename) |
| 3292 |
dep_file = compiler.depfile_for_object(rel_obj) |
| 3293 |
|
| 3294 |
# Add MSVC debug file generation compile flags: /Fd /FS |
| 3295 |
commands += self.get_compile_debugfile_args(compiler, target, rel_obj) |
| 3296 |
|
| 3297 |
# PCH handling. We only support PCH for C and C++ |
| 3298 |
if compiler.language in {'c', 'cpp'} and target.has_pch() and self.target_uses_pch(target): |
| 3299 |
pchlist = target.pch[compiler.language] |
| 3300 |
else: |
| 3301 |
pchlist = None |
| 3302 |
pch_dep: T.List[str] |
| 3303 |
if not pchlist: |
| 3304 |
pch_dep = [] |
| 3305 |
elif compiler.id == 'intel': |
| 3306 |
pch_dep = [] |
| 3307 |
else: |
| 3308 |
arr = [] |
| 3309 |
i = os.path.join(self.get_target_private_dir(target), compiler.get_pch_name(pchlist[0])) |
| 3310 |
arr.append(i) |
| 3311 |
pch_dep = arr |
| 3312 |
# If TASKING compiler family is used and MIL linking is enabled for the target, |
| 3313 |
# then compilation rule name is a special one to output MIL files |
| 3314 |
# instead of object files for .c files |
| 3315 |
if compiler.get_id() == 'tasking': |
| 3316 |
target_lto = self.get_target_option(target, OptionKey('b_lto', machine=target.for_machine, subproject=target.subproject)) |
| 3317 |
if ((isinstance(target, build.StaticLibrary) and target.prelink) or target_lto) and src.rsplit('.', 1)[1] in compilers.lang_suffixes['c']: |
| 3318 |
compiler_name = self.get_compiler_rule_name('tasking_mil_compile', compiler.for_machine) |
| 3319 |
else: |
| 3320 |
compiler_name = self.compiler_to_rule_name(compiler) |
| 3321 |
else: |
| 3322 |
compiler_name = self.compiler_to_rule_name(compiler) |
| 3323 |
extra_deps = self.get_target_depend_files(target).copy() |
| 3324 |
if compiler.get_language() == 'fortran': |
| 3325 |
# Can't read source file to scan for deps if it's generated later |
| 3326 |
# at build-time. Skip scanning for deps, and just set the module |
| 3327 |
# outdir argument instead. |
| 3328 |
# https://github.com/mesonbuild/meson/issues/1348 |
| 3329 |
if not is_generated: |
| 3330 |
abs_src = Path(build_dir) / rel_src |
| 3331 |
extra_deps += self.get_fortran_deps(T.cast('FortranCompiler', compiler), |
| 3332 |
abs_src, target) |
| 3333 |
if not self.use_dyndeps_for_fortran(): |
| 3334 |
# Dependency hack. Remove once multiple outputs in Ninja is fixed: |
| 3335 |
# https://groups.google.com/forum/#!topic/ninja-build/j-2RfBIOd_8 |
| 3336 |
for modname, srcfile in self.fortran_deps[target.get_basename()].items(): |
| 3337 |
modfile = os.path.join(self.get_target_private_dir(target), |
| 3338 |
compiler.module_name_to_filename(modname)) |
| 3339 |
|
| 3340 |
if srcfile == src: |
| 3341 |
crstr = self.get_rule_suffix(target.for_machine) |
| 3342 |
depelem = NinjaBuildElement(self.all_outputs, |
| 3343 |
modfile, |
| 3344 |
'FORTRAN_DEP_HACK' + crstr, |
| 3345 |
rel_obj) |
| 3346 |
self.add_build(depelem) |
| 3347 |
commands += compiler.get_module_outdir_args(self.get_target_private_dir(target)) |
| 3348 |
|
| 3349 |
# C++ import std is complicated enough to get its own method. |
| 3350 |
istd_args, istd_dep = self.handle_cpp_import_std(target, compiler) |
| 3351 |
commands.extend(istd_args) |
| 3352 |
header_deps += istd_dep |
| 3353 |
if extra_args is not None: |
| 3354 |
commands.extend(extra_args) |
| 3355 |
|
| 3356 |
element = NinjaBuildElement(self.all_outputs, rel_obj, compiler_name, rel_src) |
| 3357 |
self.add_header_deps(target, element, header_deps) |
| 3358 |
for d in extra_deps: |
| 3359 |
element.add_dep(d) |
| 3360 |
element.add_orderdep(self.order_deps_to_strings(target, order_deps)) |
| 3361 |
element.add_dep(pch_dep) |
| 3362 |
if not self.use_dyndeps_for_fortran(): |
| 3363 |
for i in self.get_fortran_module_deps(target, compiler): |
| 3364 |
element.add_dep(i) |
| 3365 |
if dep_file: |
| 3366 |
element.add_item('DEPFILE', dep_file) |
| 3367 |
if compiler.get_language() == 'cuda': |
| 3368 |
# for cuda, we manually escape target name ($out) as $CUDA_ESCAPED_TARGET because nvcc doesn't support `-MQ` flag |
| 3369 |
def quote_make_target(targetName: str) -> str: |
| 3370 |
# this escape implementation is taken from llvm |
| 3371 |
result = '' |
| 3372 |
for (i, c) in enumerate(targetName): |
| 3373 |
if c in {' ', '\t'}: |
| 3374 |
# Escape the preceding backslashes |
| 3375 |
for j in range(i - 1, -1, -1): |
| 3376 |
if targetName[j] == '\\': |
| 3377 |
result += '\\' |
| 3378 |
else: |
| 3379 |
break |
| 3380 |
# Escape the space/tab |
| 3381 |
result += '\\' |
| 3382 |
elif c == '$': |
| 3383 |
result += '$' |
| 3384 |
elif c == '#': |
| 3385 |
result += '\\' |
| 3386 |
result += c |
| 3387 |
return result |
| 3388 |
element.add_item('CUDA_ESCAPED_TARGET', quote_make_target(rel_obj)) |
| 3389 |
if self.ninja.should_use_rspfile(element) and compiler.rsp_file_syntax() == RSPFileSyntax.NASM: |
| 3390 |
exe = compiler.get_exelist() |
| 3391 |
# Add to commands the args created by generate_compile_rule_for(). |
| 3392 |
# commands remain separate from exelist because they must stay |
| 3393 |
# a CompilerArgs. |
| 3394 |
if dep_file: |
| 3395 |
commands += compiler.get_dependency_gen_args(rel_obj, dep_file) |
| 3396 |
commands += [*compiler.get_output_args(rel_obj), *compiler.get_compile_only_args(), rel_src] |
| 3397 |
|
| 3398 |
element.rulename = 'CUSTOM_COMMAND' |
| 3399 |
meson_exe_cmd, reason = self.as_meson_exe_cmdline(exe[0], |
| 3400 |
exe[1:] + commands.to_native(), |
| 3401 |
separator='\n', |
| 3402 |
rsp_file_flag='-@', |
| 3403 |
can_use_rsp_file=True, |
| 3404 |
verbose=True) |
| 3405 |
cmd_type = f' (wrapped by meson {reason})' if reason else '' |
| 3406 |
element.add_item('COMMAND', meson_exe_cmd) |
| 3407 |
element.add_item('description', f'Compiling {compiler.get_display_language()} object {rel_obj}{cmd_type}') |
| 3408 |
else: |
| 3409 |
element.add_item('ARGS', commands) |
| 3410 |
|
| 3411 |
self.add_dependency_scanner_entries_to_element(target, compiler, element, src) |
| 3412 |
self.add_build(element) |
| 3413 |
assert isinstance(rel_obj, str) |
| 3414 |
assert isinstance(rel_src, str) |
| 3415 |
return (rel_obj, rel_src.replace('\\', '/')) |
| 3416 |
|
| 3417 |
def target_uses_import_std(self, target: build.BuildTarget) -> bool: |
| 3418 |
if 'cpp' not in target.compilers: |
| 3419 |
return False |
| 3420 |
try: |
| 3421 |
if self.environment.coredata.get_option_for_target(target, 'cpp_importstd') == 'true': |
| 3422 |
return True |
| 3423 |
except KeyError: |
| 3424 |
pass |
| 3425 |
return False |
| 3426 |
|
| 3427 |
def handle_cpp_import_std(self, target: build.BuildTarget, compiler: Compiler) -> T.Tuple[T.List[str], T.List[File]]: |
| 3428 |
istd_args: T.List[str] = [] |
| 3429 |
istd_dep: T.List[File] = [] |
| 3430 |
if not self.target_uses_import_std(target): |
| 3431 |
return istd_args, istd_dep |
| 3432 |
mlog.warning('Import std support is experimental and might break compatibility in the future.') |
| 3433 |
# At the time of writing, all three major compilers work |
| 3434 |
# wildly differently. Keep this isolated here until things |
| 3435 |
# consolidate. |
| 3436 |
if compiler.id == 'gcc': |
| 3437 |
if self.import_std is None: |
| 3438 |
mod_file = 'gcm.cache/std.gcm' |
| 3439 |
mod_obj_file = 'std.o' |
| 3440 |
elem = NinjaBuildElement(self.all_outputs, [mod_file, mod_obj_file], 'CUSTOM_COMMAND', []) |
| 3441 |
compile_args = compiler.get_option_compile_args(target, target.subproject) |
| 3442 |
compile_args += compiler.get_option_std_args(target, target.subproject) |
| 3443 |
compile_args += ['-c', '-fmodules', '-fsearch-include-path', 'bits/std.cc'] |
| 3444 |
elem.add_item('COMMAND', compiler.exelist + compile_args) |
| 3445 |
self.add_build(elem) |
| 3446 |
self.import_std = ImportStdInfo(elem, mod_file, [mod_obj_file]) |
| 3447 |
istd_args = ['-fmodules'] |
| 3448 |
istd_dep = [File(True, '', self.import_std.gen_module_file)] |
| 3449 |
return istd_args, istd_dep |
| 3450 |
elif compiler.id == 'msvc': |
| 3451 |
if self.import_std is None: |
| 3452 |
mod_file = 'std.ifc' |
| 3453 |
mod_obj_file = 'std.obj' |
| 3454 |
in_file = Path(os.environ['VCToolsInstallDir']) / 'modules/std.ixx' |
| 3455 |
if not in_file.is_file(): |
| 3456 |
raise SystemExit('VS std import header could not be located.') |
| 3457 |
in_file_str = str(in_file) |
| 3458 |
elem = NinjaBuildElement(self.all_outputs, [mod_file, mod_obj_file], 'CUSTOM_COMMAND', [in_file_str]) |
| 3459 |
compile_args = compiler.get_option_compile_args(target, target.subproject) |
| 3460 |
compile_args += compiler.get_option_std_args(target, target.subproject) |
| 3461 |
compile_args += ['/nologo', '/c', '/O2', in_file_str] |
| 3462 |
elem.add_item('COMMAND', compiler.exelist + compile_args) |
| 3463 |
self.add_build(elem) |
| 3464 |
self.import_std = ImportStdInfo(elem, mod_file, [mod_obj_file]) |
| 3465 |
istd_dep = [File(True, '', self.import_std.gen_module_file)] |
| 3466 |
return istd_args, istd_dep |
| 3467 |
else: |
| 3468 |
raise MesonException(f'Import std not supported on compiler {compiler.id} yet.') |
| 3469 |
|
| 3470 |
def add_dependency_scanner_entries_to_element(self, target: build.BuildTarget, compiler: Compiler, element: NinjaBuildElement, src: File) -> None: |
| 3471 |
if not self.should_use_dyndeps_for_target(target): |
| 3472 |
return |
| 3473 |
if isinstance(target, build.CompileTarget): |
| 3474 |
return |
| 3475 |
extension = os.path.splitext(src.fname)[1][1:] |
| 3476 |
if extension != 'C': |
| 3477 |
extension = extension.lower() |
| 3478 |
if not (extension in compilers.lang_suffixes['fortran'] or extension in compilers.lang_suffixes['cpp']): |
| 3479 |
return |
| 3480 |
dep_scan_file = self.get_dep_scan_file_for(target)[1] |
| 3481 |
element.add_item('dyndep', dep_scan_file) |
| 3482 |
element.add_orderdep(dep_scan_file) |
| 3483 |
|
| 3484 |
def get_dep_scan_file_for(self, target: build.BuildTarget) -> T.Tuple[str, str]: |
| 3485 |
priv = self.get_target_private_dir(target) |
| 3486 |
return os.path.join(priv, 'depscan.json'), os.path.join(priv, 'depscan.dd') |
| 3487 |
|
| 3488 |
def add_header_deps(self, target: build.BuildTarget, ninja_element: NinjaBuildElement, header_deps: T.List[FileOrString]) -> None: |
| 3489 |
for d in header_deps: |
| 3490 |
if isinstance(d, File): |
| 3491 |
d = d.rel_to_builddir(self.build_to_src) |
| 3492 |
elif not self.has_dir_part(d): |
| 3493 |
d = os.path.join(self.get_target_private_dir(target), d) |
| 3494 |
ninja_element.add_orderdep(d) |
| 3495 |
|
| 3496 |
def has_dir_part(self, fname: FileOrString) -> bool: |
| 3497 |
# FIXME FIXME: The usage of this is a terrible and unreliable hack |
| 3498 |
if isinstance(fname, File): |
| 3499 |
return fname.subdir != '' |
| 3500 |
return has_path_sep(fname) |
| 3501 |
|
| 3502 |
# Fortran is a bit weird (again). When you link against a library, just compiling a source file |
| 3503 |
# requires the mod files that are output when single files are built. To do this right we would need to |
| 3504 |
# scan all inputs and write out explicit deps for each file. That is too slow and too much effort so |
| 3505 |
# instead just have a full dependency on the library. This ensures all required mod files are created. |
| 3506 |
# The real deps are then detected via dep file generation from the compiler. This breaks on compilers that |
| 3507 |
# produce incorrect dep files but such is life. A full dependency is |
| 3508 |
# required to ensure that if a new module is added to an existing file that |
| 3509 |
# we correctly rebuild |
| 3510 |
def get_fortran_module_deps(self, target: build.BuildTarget, compiler: Compiler) -> T.List[str]: |
| 3511 |
# If we have dyndeps then we don't need this, since the depscanner will |
| 3512 |
# do all of things described above. |
| 3513 |
if compiler.language != 'fortran' or self.use_dyndeps_for_fortran(): |
| 3514 |
return [] |
| 3515 |
return [ |
| 3516 |
os.path.join(self.get_target_dir(lt), lt.get_filename()) |
| 3517 |
for lt in itertools.chain(target.link_targets, target.link_whole_targets) |
| 3518 |
] |
| 3519 |
|
| 3520 |
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]: |
| 3521 |
from ..compilers.mixins.visualstudio import VisualStudioLikeCompiler |
| 3522 |
assert isinstance(compiler, VisualStudioLikeCompiler) # for mypy |
| 3523 |
header = pch[0] |
| 3524 |
pchname = compiler.get_pch_name(header) |
| 3525 |
dst = os.path.join(self.get_target_private_dir(target), pchname) |
| 3526 |
|
| 3527 |
commands: T.List[str] = [] |
| 3528 |
commands += self.generate_basic_compiler_args(target, compiler) |
| 3529 |
|
| 3530 |
if pch[1] is None: |
| 3531 |
# Auto generate PCH. |
| 3532 |
source = self.create_msvc_pch_implementation(target, compiler.get_language(), pch[0]) |
| 3533 |
pch_header_dir = os.path.dirname(os.path.join(self.build_to_src, target.get_subdir(), header)) |
| 3534 |
commands += compiler.get_include_args(pch_header_dir, False) |
| 3535 |
else: |
| 3536 |
source = os.path.join(self.build_to_src, target.get_subdir(), pch[1]) |
| 3537 |
|
| 3538 |
just_name = os.path.basename(header) |
| 3539 |
(objname, pch_args) = compiler.gen_pch_args(just_name, source, dst) |
| 3540 |
commands += pch_args |
| 3541 |
commands += self._generate_single_compile(target, compiler) |
| 3542 |
commands += self.get_compile_debugfile_args(compiler, target, objname) |
| 3543 |
dep = dst + '.' + compiler.get_depfile_suffix() |
| 3544 |
|
| 3545 |
link_objects = [objname] if compiler.should_link_pch_object() else [] |
| 3546 |
|
| 3547 |
return commands, dep, dst, link_objects, source |
| 3548 |
|
| 3549 |
def generate_gcc_pch_command(self, target: build.BuildTarget, compiler: Compiler, pch: str) -> T.Tuple[CompilerArgs, str, str, T.List[str]]: |
| 3550 |
commands = self._generate_single_compile(target, compiler) |
| 3551 |
if pch.split('.')[-1] == 'h' and compiler.language == 'cpp': |
| 3552 |
# Explicitly compile pch headers as C++. If Clang is invoked in C++ mode, it actually warns if |
| 3553 |
# this option is not set, and for gcc it also makes sense to use it. |
| 3554 |
commands += ['-x', 'c++-header'] |
| 3555 |
dst = os.path.join(self.get_target_private_dir(target), |
| 3556 |
os.path.basename(pch) + '.' + compiler.get_pch_suffix()) |
| 3557 |
dep = dst + '.' + compiler.get_depfile_suffix() |
| 3558 |
return commands, dep, dst, [] # Gcc does not create an object file during pch generation. |
| 3559 |
|
| 3560 |
def generate_mwcc_pch_command(self, target: build.BuildTarget, compiler: Compiler, pch: str) -> T.Tuple[CompilerArgs, str, str, T.List[str]]: |
| 3561 |
commands = self._generate_single_compile(target, compiler) |
| 3562 |
dst = os.path.join(self.get_target_private_dir(target), |
| 3563 |
os.path.basename(pch) + '.' + compiler.get_pch_suffix()) |
| 3564 |
dep = os.path.splitext(dst)[0] + '.' + compiler.get_depfile_suffix() |
| 3565 |
return commands, dep, dst, [] # mwcc compilers do not create an object file during pch generation. |
| 3566 |
|
| 3567 |
def generate_pch(self, target: build.BuildTarget, header_deps: T.Optional[T.List[FileOrString]] = None) -> T.List[str]: |
| 3568 |
header_deps = header_deps if header_deps is not None else [] |
| 3569 |
pch_objects = [] |
| 3570 |
for lang in T.cast('T.Tuple[Language, ...]', ('c', 'cpp')): |
| 3571 |
pch = target.pch[lang] |
| 3572 |
if not pch: |
| 3573 |
continue |
| 3574 |
if lang not in target.compilers: |
| 3575 |
continue |
| 3576 |
compiler: Compiler = target.compilers[lang] |
| 3577 |
if compiler.get_argument_syntax() == 'msvc': |
| 3578 |
(commands, dep, dst, objs, src) = self.generate_msvc_pch_command(target, compiler, pch) |
| 3579 |
extradep = os.path.join(self.build_to_src, target.get_subdir(), pch[0]) |
| 3580 |
elif compiler.id == 'intel': |
| 3581 |
# Intel generates on target generation |
| 3582 |
continue |
| 3583 |
elif 'mwcc' in compiler.id: |
| 3584 |
src = os.path.join(self.build_to_src, target.get_subdir(), pch[0]) |
| 3585 |
(commands, dep, dst, objs) = self.generate_mwcc_pch_command(target, compiler, pch[0]) |
| 3586 |
extradep = None |
| 3587 |
else: |
| 3588 |
src = os.path.join(self.build_to_src, target.get_subdir(), pch[0]) |
| 3589 |
(commands, dep, dst, objs) = self.generate_gcc_pch_command(target, compiler, pch[0]) |
| 3590 |
extradep = None |
| 3591 |
pch_objects += objs |
| 3592 |
rulename = self.compiler_to_pch_rule_name(compiler) |
| 3593 |
elem = NinjaBuildElement(self.all_outputs, objs + [dst], rulename, src) |
| 3594 |
if extradep is not None: |
| 3595 |
elem.add_dep(extradep) |
| 3596 |
self.add_header_deps(target, elem, header_deps) |
| 3597 |
elem.add_item('ARGS', commands) |
| 3598 |
elem.add_item('DEPFILE', dep) |
| 3599 |
self.add_build(elem) |
| 3600 |
self.all_pch[compiler.id].update(objs + [dst]) |
| 3601 |
return pch_objects |
| 3602 |
|
| 3603 |
def get_target_shsym_filename(self, target: build.BuildTarget) -> str: |
| 3604 |
# Always name the .symbols file after the primary build output because it always exists |
| 3605 |
targetdir = self.get_target_private_dir(target) |
| 3606 |
return os.path.join(targetdir, target.get_filename() + '.symbols') |
| 3607 |
|
| 3608 |
def generate_shsym(self, target: build.BuildTarget) -> None: |
| 3609 |
# On OS/2, an import library is generated after linking a DLL, so |
| 3610 |
# if a DLL is used as a target, import library is not generated. |
| 3611 |
if self.environment.machines[target.for_machine].is_os2(): |
| 3612 |
target_file = self.get_target_filename_for_linking(target) |
| 3613 |
else: |
| 3614 |
target_file = self.get_target_filename(target) |
| 3615 |
if isinstance(target, build.SharedLibrary) and target.aix_so_archive: |
| 3616 |
if self.environment.machines[target.for_machine].is_aix(): |
| 3617 |
linker, stdlib_args = target.get_clink_dynamic_linker_and_stdlibs() |
| 3618 |
target.get_outputs()[0] = linker.get_archive_name(target.get_outputs()[0]) |
| 3619 |
target_file = target.get_outputs()[0] |
| 3620 |
target_file = os.path.join(self.get_target_dir(target), target_file) |
| 3621 |
symname = self.get_target_shsym_filename(target) |
| 3622 |
elem = NinjaBuildElement(self.all_outputs, symname, 'SHSYM', target_file) |
| 3623 |
# The library we will actually link to, which is an import library on Windows (not the DLL) |
| 3624 |
elem.add_item('IMPLIB', self.get_target_filename_for_linking(target)) |
| 3625 |
if self.environment.is_cross_build(): |
| 3626 |
elem.add_item('CROSS', '--cross-host=' + self.environment.machines[target.for_machine].system) |
| 3627 |
self.add_build(elem) |
| 3628 |
|
| 3629 |
def get_import_filename(self, target: build.Executable | build.SharedLibrary) -> str: |
| 3630 |
return os.path.join(self.get_target_dir(target), target.import_filename) |
| 3631 |
|
| 3632 |
def get_target_type_link_args(self, target: build.BuildTarget, linker: T.Union[StaticLinker, Compiler]) -> T.List[str]: |
| 3633 |
if isinstance(target, build.StaticLibrary): |
| 3634 |
produce_thin_archive = self.allow_thin_archives[target.for_machine] and not target.should_install() |
| 3635 |
return linker.get_std_link_args(self.environment, produce_thin_archive) |
| 3636 |
|
| 3637 |
assert isinstance(linker, Compiler) |
| 3638 |
commands: T.List[str] = [] |
| 3639 |
if isinstance(target, build.Executable): |
| 3640 |
# Currently only used with the Swift compiler to add '-emit-executable' |
| 3641 |
commands += linker.get_std_exe_link_args() |
| 3642 |
# If export_dynamic, add the appropriate linker arguments |
| 3643 |
if target.export_dynamic: |
| 3644 |
commands += linker.gen_export_dynamic_link_args() |
| 3645 |
# If implib, and that's significant on this platform (i.e. Windows using either GCC or Visual Studio) |
| 3646 |
if target.import_filename: |
| 3647 |
commands += linker.gen_import_library_args(self.get_import_filename(target)) |
| 3648 |
if target.pie: |
| 3649 |
commands += linker.get_pie_link_args() |
| 3650 |
if target.vs_module_defs: |
| 3651 |
commands += linker.gen_vs_module_defs_args(target.vs_module_defs.rel_to_builddir(self.build_to_src)) |
| 3652 |
elif isinstance(target, build.SharedLibrary): |
| 3653 |
if isinstance(target, build.SharedModule): |
| 3654 |
commands += linker.get_std_shared_module_link_args(target) |
| 3655 |
else: |
| 3656 |
commands += linker.get_std_shared_lib_link_args() |
| 3657 |
# All shared libraries are PIC |
| 3658 |
commands += linker.get_pic_args() |
| 3659 |
# Add -Wl,-soname arguments on Linux, -install_name on OS X |
| 3660 |
if not isinstance(target, build.SharedModule) or target.force_soname: |
| 3661 |
commands += linker.get_soname_args( |
| 3662 |
target.prefix, target.name, target.suffix, |
| 3663 |
target.soversion, target.darwin_versions) |
| 3664 |
if target.vs_module_defs: |
| 3665 |
commands += linker.gen_vs_module_defs_args(target.vs_module_defs.rel_to_builddir(self.build_to_src)) |
| 3666 |
# This is only visited when building for Windows using either GCC or Visual Studio |
| 3667 |
if target.import_filename: |
| 3668 |
commands += linker.gen_import_library_args(self.get_import_filename(target)) |
| 3669 |
else: |
| 3670 |
raise RuntimeError('Unknown build target type.') |
| 3671 |
return commands |
| 3672 |
|
| 3673 |
def get_target_type_link_args_post_dependencies(self, target: build.BuildTarget, linker: T.Union[Compiler, StaticLinker]) -> T.List[str]: |
| 3674 |
commands: T.List[str] = [] |
| 3675 |
if isinstance(target, (build.Executable, build.SharedLibrary)): |
| 3676 |
assert isinstance(linker, Compiler) |
| 3677 |
|
| 3678 |
# If win_subsystem is significant on this platform, add the appropriate linker arguments. |
| 3679 |
# Unfortunately this can't be done in get_target_type_link_args, because some misguided |
| 3680 |
# libraries (such as SDL2) add -mwindows to their link flags. |
| 3681 |
m = self.environment.machines[target.for_machine] |
| 3682 |
if m.is_windows() or m.is_cygwin(): |
| 3683 |
commands += linker.get_win_subsystem_args(target.win_subsystem) |
| 3684 |
return commands |
| 3685 |
|
| 3686 |
def get_link_whole_args(self, linker: Compiler, target: build.BuildTarget) -> T.List[str]: |
| 3687 |
use_custom = False |
| 3688 |
if linker.id == 'msvc': |
| 3689 |
# Expand our object lists manually if we are on pre-Visual Studio 2015 Update 2 |
| 3690 |
# (incidentally, the "linker" here actually refers to cl.exe) |
| 3691 |
if mesonlib.version_compare(linker.version, '<19.00.23918'): |
| 3692 |
use_custom = True |
| 3693 |
|
| 3694 |
if use_custom: |
| 3695 |
objects_from_static_libs: T.List[str] = [] |
| 3696 |
for dep in target.link_whole_targets: |
| 3697 |
if not isinstance(dep, build.BuildTarget): |
| 3698 |
raise MesonException( |
| 3699 |
f'Cannot extract objects from custom target {dep.name!r} to ' |
| 3700 |
f'link_whole it into {target.name!r}: this is not supported ' |
| 3701 |
'with versions of MSVC older than Visual Studio 2015 Update 2.') |
| 3702 |
l = dep.extract_all_objects(False) |
| 3703 |
objects_from_static_libs += self.determine_ext_objs(l) |
| 3704 |
objects_from_static_libs.extend(self.flatten_object_list(dep)[0]) |
| 3705 |
|
| 3706 |
return objects_from_static_libs |
| 3707 |
else: |
| 3708 |
target_args = self.build_target_link_arguments(linker, target.link_whole_targets) |
| 3709 |
return linker.get_link_whole_for(target_args) if target_args else [] |
| 3710 |
|
| 3711 |
@lru_cache(maxsize=None) |
| 3712 |
def guess_library_absolute_path(self, linker: Compiler, libname: str, search_dirs: T.Tuple[str, ...], patterns: T.Tuple[str, ...]) -> T.Optional[Path]: |
| 3713 |
from ..compilers.c import CCompiler |
| 3714 |
for d in search_dirs: |
| 3715 |
for p in patterns: |
| 3716 |
trial = CCompiler._get_trials_from_pattern(p, d, libname) |
| 3717 |
if not trial: |
| 3718 |
continue |
| 3719 |
trial = CCompiler._get_file_from_list(self.environment, trial) |
| 3720 |
if not trial: |
| 3721 |
continue |
| 3722 |
# Return the first result |
| 3723 |
return trial |
| 3724 |
return None |
| 3725 |
|
| 3726 |
def guess_external_link_dependencies(self, linker: Compiler, target: build.BuildTarget, commands: CompilerArgs, internal: T.List[str]) -> T.List[str]: |
| 3727 |
# Ideally the linker would generate dependency information that could be used. |
| 3728 |
# But that has 2 problems: |
| 3729 |
# * currently ld cannot create dependency information in a way that ninja can use: |
| 3730 |
# https://sourceware.org/bugzilla/show_bug.cgi?id=22843 |
| 3731 |
# * Meson optimizes libraries from the same build using the symbol extractor. |
| 3732 |
# Just letting ninja use ld generated dependencies would undo this optimization. |
| 3733 |
search_dirs: OrderedSet[str] = OrderedSet() |
| 3734 |
libs: OrderedSet[str] = OrderedSet() |
| 3735 |
absolute_libs = [] |
| 3736 |
|
| 3737 |
build_dir = self.environment.get_build_dir() |
| 3738 |
# the following loop sometimes consumes two items from command in one pass |
| 3739 |
it = iter(linker.native_args_to_unix(list(commands))) |
| 3740 |
for item in it: |
| 3741 |
if item in internal and not item.startswith('-'): |
| 3742 |
continue |
| 3743 |
|
| 3744 |
if item.startswith('-L'): |
| 3745 |
if len(item) > 2: |
| 3746 |
path = item[2:] |
| 3747 |
else: |
| 3748 |
try: |
| 3749 |
path = next(it) |
| 3750 |
except StopIteration: |
| 3751 |
mlog.warning("Generated linker command has -L argument without following path") |
| 3752 |
break |
| 3753 |
if not os.path.isabs(path): |
| 3754 |
path = os.path.join(build_dir, path) |
| 3755 |
search_dirs.add(path) |
| 3756 |
elif item.startswith('-l'): |
| 3757 |
if len(item) > 2: |
| 3758 |
lib = item[2:] |
| 3759 |
else: |
| 3760 |
try: |
| 3761 |
lib = next(it) |
| 3762 |
except StopIteration: |
| 3763 |
mlog.warning("Generated linker command has '-l' argument without following library name") |
| 3764 |
break |
| 3765 |
libs.add(lib) |
| 3766 |
elif os.path.isabs(item) and compilers.is_library(item) and os.path.isfile(item): |
| 3767 |
absolute_libs.append(item) |
| 3768 |
|
| 3769 |
guessed_dependencies = [] |
| 3770 |
# TODO The get_library_naming requirement currently excludes link targets that use d or fortran as their main linker |
| 3771 |
try: |
| 3772 |
static_patterns = linker.get_library_naming(LibType.STATIC, strict=True) |
| 3773 |
shared_patterns = linker.get_library_naming(LibType.SHARED, strict=True) |
| 3774 |
search_dirs_tuple = tuple(search_dirs) + tuple(linker.get_library_dirs()) |
| 3775 |
for libname in libs: |
| 3776 |
# be conservative and record most likely shared and static resolution, because we don't know exactly |
| 3777 |
# which one the linker will prefer |
| 3778 |
staticlibs = self.guess_library_absolute_path(linker, libname, |
| 3779 |
search_dirs_tuple, static_patterns) |
| 3780 |
sharedlibs = self.guess_library_absolute_path(linker, libname, |
| 3781 |
search_dirs_tuple, shared_patterns) |
| 3782 |
if staticlibs: |
| 3783 |
guessed_dependencies.append(staticlibs.resolve().as_posix()) |
| 3784 |
if sharedlibs: |
| 3785 |
guessed_dependencies.append(sharedlibs.resolve().as_posix()) |
| 3786 |
except (mesonlib.MesonException, AttributeError) as e: |
| 3787 |
if 'get_library_naming' not in str(e): |
| 3788 |
raise |
| 3789 |
|
| 3790 |
return guessed_dependencies + absolute_libs |
| 3791 |
|
| 3792 |
def generate_prelink(self, target: build.BuildTarget, obj_list: T.List[str]) -> T.List[str]: |
| 3793 |
assert isinstance(target, build.StaticLibrary) |
| 3794 |
prelink_name = os.path.join(self.get_target_private_dir(target), target.name + '-prelink.o') |
| 3795 |
elem = NinjaBuildElement(self.all_outputs, [prelink_name], 'CUSTOM_COMMAND', obj_list) |
| 3796 |
|
| 3797 |
prelinker = target.get_prelinker() |
| 3798 |
cmd = prelinker.exelist[:] |
| 3799 |
obj_list, args = prelinker.get_prelink_args(prelink_name, obj_list) |
| 3800 |
cmd += args |
| 3801 |
if prelinker.get_prelink_append_compile_args(): |
| 3802 |
compile_args = target.get_single_compile_base_args(prelinker) |
| 3803 |
compile_args += self._generate_single_compile_target_args(target, prelinker) |
| 3804 |
compile_args = compile_args.compiler.compiler_args(compile_args) |
| 3805 |
cmd += compile_args.to_native() |
| 3806 |
|
| 3807 |
cmd = self.replace_paths(target, cmd) |
| 3808 |
elem.add_item('COMMAND', cmd) |
| 3809 |
elem.add_item('description', f'Prelinking {prelink_name}') |
| 3810 |
self.add_build(elem) |
| 3811 |
return obj_list |
| 3812 |
|
| 3813 |
def get_build_rpath_args(self, target: build.BuildTarget, linker: T.Union[Compiler, StaticLinker]) -> T.List[str]: |
| 3814 |
if has_path_sep(target.name): |
| 3815 |
# Target names really should not have slashes in them, but |
| 3816 |
# unfortunately we did not check for that and some downstream projects |
| 3817 |
# now have them. Once slashes are forbidden, remove this bit. |
| 3818 |
target_slashname_workaround_dir = os.path.join(os.path.dirname(target.name), |
| 3819 |
self.get_target_dir(target)) |
| 3820 |
else: |
| 3821 |
target_slashname_workaround_dir = self.get_target_dir(target) |
| 3822 |
(rpath_args, target.rpath_dirs_to_remove) = ( |
| 3823 |
linker.build_rpath_args(self.environment.get_build_dir(), |
| 3824 |
target_slashname_workaround_dir, |
| 3825 |
target)) |
| 3826 |
return rpath_args |
| 3827 |
|
| 3828 |
def generate_link(self, target: build.BuildTarget, outname: str, obj_list: T.List[str], |
| 3829 |
linker: T.Union[Compiler, StaticLinker], |
| 3830 |
extra_objs: T.Optional[T.List[str]] = None, |
| 3831 |
stdlib_args: T.Optional[T.List[str]] = None) -> NinjaBuildElement: |
| 3832 |
extra_objs = extra_objs if extra_objs is not None else [] |
| 3833 |
stdlib_args = stdlib_args if stdlib_args is not None else [] |
| 3834 |
implicit_outs = [] |
| 3835 |
if isinstance(target, build.StaticLibrary): |
| 3836 |
linker_base = 'STATIC' |
| 3837 |
else: |
| 3838 |
assert isinstance(linker, Compiler) |
| 3839 |
linker_base = linker.get_language() # Fixme. |
| 3840 |
if isinstance(target, build.SharedLibrary) and self.environment.machines[target.for_machine].is_os2(): |
| 3841 |
target_file = self.get_target_filename(target) |
| 3842 |
import_name = self.get_import_filename(target) |
| 3843 |
elem = NinjaBuildElement(self.all_outputs, import_name, 'IMPORTLIB', target_file) |
| 3844 |
self.add_build(elem) |
| 3845 |
crstr = self.get_rule_suffix(target.for_machine) |
| 3846 |
linker_rule = linker_base + '_LINKER' + crstr |
| 3847 |
# Create an empty commands list, and start adding link arguments from |
| 3848 |
# various sources in the order in which they must override each other |
| 3849 |
# starting from hard-coded defaults followed by build options and so on. |
| 3850 |
# |
| 3851 |
# Once all the linker options have been passed, we will start passing |
| 3852 |
# libraries and library paths from internal and external sources. |
| 3853 |
commands = linker.compiler_args() |
| 3854 |
# First, the trivial ones that are impossible to override. |
| 3855 |
# |
| 3856 |
# Add linker args for linking this target derived from 'base' build |
| 3857 |
# options passed on the command-line, in default_options, etc. |
| 3858 |
# These have the lowest priority. |
| 3859 |
if isinstance(target, build.StaticLibrary): |
| 3860 |
assert isinstance(linker, StaticLinker) |
| 3861 |
base_link_args = linker.get_base_link_args(target, linker, self.environment) |
| 3862 |
else: |
| 3863 |
assert isinstance(linker, Compiler) |
| 3864 |
base_link_args = compilers.get_base_link_args(target, |
| 3865 |
linker, |
| 3866 |
self.environment) |
| 3867 |
commands += self.transform_link_args(target, base_link_args) |
| 3868 |
# Add -nostdlib if needed; can't be overridden |
| 3869 |
commands += self.get_no_stdlib_link_args(target, linker) |
| 3870 |
# Add things like /NOLOGO; usually can't be overridden |
| 3871 |
commands += linker.get_linker_always_args() |
| 3872 |
# Add buildtype linker args: optimization level, etc. |
| 3873 |
optimization = self.get_target_option(target, 'optimization') |
| 3874 |
assert isinstance(optimization, str) |
| 3875 |
commands += linker.get_optimization_link_args(optimization) |
| 3876 |
# Add /DEBUG and the pdb filename when using MSVC |
| 3877 |
if self.get_target_option(target, 'debug'): |
| 3878 |
commands += self.get_link_debugfile_args(linker, target) |
| 3879 |
debugfile = self.get_link_debugfile_name(linker, target) |
| 3880 |
if debugfile is not None: |
| 3881 |
implicit_outs += [debugfile] |
| 3882 |
# Add link args specific to this BuildTarget type, such as soname args, |
| 3883 |
# PIC, import library generation, etc. |
| 3884 |
commands += self.get_target_type_link_args(target, linker) |
| 3885 |
if not isinstance(target, build.StaticLibrary): |
| 3886 |
assert isinstance(linker, Compiler) |
| 3887 |
# Archives that are copied wholesale in the result. Must be before any |
| 3888 |
# other link targets so missing symbols from whole archives are found in those. |
| 3889 |
commands += self.get_link_whole_args(linker, target) |
| 3890 |
commands += linker.get_build_link_args(target, self.build) |
| 3891 |
|
| 3892 |
# Now we will add libraries and library paths from various sources |
| 3893 |
|
| 3894 |
# Set runtime-paths so we can run executables without needing to set |
| 3895 |
# LD_LIBRARY_PATH, etc in the environment. Doesn't work on Windows. |
| 3896 |
commands += self.get_build_rpath_args(target, linker) |
| 3897 |
|
| 3898 |
# Add link args to link to all internal libraries (link_with:) and |
| 3899 |
# internal dependencies needed by this target. |
| 3900 |
dep_targets: T.List[str] = [] |
| 3901 |
dependencies: T.Iterable[build.BuildTargetTypes] |
| 3902 |
if isinstance(target, build.StaticLibrary): |
| 3903 |
# Link arguments of static libraries are not put in the command |
| 3904 |
# line of the library. They are instead appended to the command |
| 3905 |
# line where the static library is used. |
| 3906 |
dependencies = [] |
| 3907 |
else: |
| 3908 |
# Only non-static built targets need link args and link dependencies |
| 3909 |
assert isinstance(linker, Compiler) |
| 3910 |
|
| 3911 |
dependencies = target.get_dependencies() |
| 3912 |
internal = self.build_target_link_arguments(linker, dependencies) |
| 3913 |
commands += internal |
| 3914 |
|
| 3915 |
# For 'automagic' deps: Boost and GTest. Also dependency('threads'). |
| 3916 |
# pkg-config puts the thread flags itself via `Cflags:` |
| 3917 |
commands += linker.get_target_link_args(target) |
| 3918 |
# External deps must be last because target link libraries may depend on them. |
| 3919 |
for dep in target.get_external_deps(): |
| 3920 |
# Extend without reordering or de-dup to preserve `-L -l` sets |
| 3921 |
# https://github.com/mesonbuild/meson/issues/1718 |
| 3922 |
commands.extend_preserving_lflags(linker.get_dependency_link_args(dep)) |
| 3923 |
for d in target.get_dependencies(): |
| 3924 |
if isinstance(d, build.StaticLibrary): |
| 3925 |
for dep in d.get_external_deps(): |
| 3926 |
link_args = linker.get_dependency_link_args(dep) |
| 3927 |
# Ensure that native static libraries use Unix-style naming if necessary. |
| 3928 |
# Depending on the target/linker, rustc --print native-static-libs may |
| 3929 |
# output MSVC-style names. Converting these to Unix-style is safe, as the |
| 3930 |
# list contains only native static libraries. |
| 3931 |
if dep.name == '_rust_native_static_libs' and linker.get_argument_syntax() != 'msvc': |
| 3932 |
from ..linkers.linkers import VisualStudioLikeLinker |
| 3933 |
link_args = VisualStudioLikeLinker.native_args_to_unix(link_args) |
| 3934 |
commands.extend_preserving_lflags(link_args) |
| 3935 |
|
| 3936 |
# Add link args specific to this BuildTarget type that must not be overridden by dependencies |
| 3937 |
commands += self.get_target_type_link_args_post_dependencies(target, linker) |
| 3938 |
|
| 3939 |
# Add link args for c_* or cpp_* build options. Currently this only |
| 3940 |
# adds c_winlibs and cpp_winlibs when building for Windows. This needs |
| 3941 |
# to be after all internal and external libraries so that unresolved |
| 3942 |
# symbols from those can be found here. This is needed when the |
| 3943 |
# *_winlibs that we want to link to are static mingw64 libraries. |
| 3944 |
# |
| 3945 |
# The static linker doesn't know what language it is building, so we |
| 3946 |
# don't know what option. Fortunately, it doesn't care to see the |
| 3947 |
# language-specific options either. |
| 3948 |
# |
| 3949 |
# We shouldn't check whether we are making a static library, because |
| 3950 |
# in the LTO case we do use a real compiler here. |
| 3951 |
commands += linker.get_option_link_args(target) |
| 3952 |
|
| 3953 |
dep_targets.extend(self.guess_external_link_dependencies(linker, target, commands, internal)) |
| 3954 |
|
| 3955 |
obj_list += self.get_import_std_object(target) |
| 3956 |
|
| 3957 |
# Add libraries generated by custom targets |
| 3958 |
custom_target_libraries = self.get_custom_target_provided_libraries(target) |
| 3959 |
commands += extra_objs |
| 3960 |
commands += custom_target_libraries |
| 3961 |
commands += stdlib_args # Standard library arguments go last, because they never depend on anything. |
| 3962 |
dep_targets.extend([self.get_dependency_filename(t) for t in dependencies]) |
| 3963 |
dep_targets.extend([self.get_dependency_filename(t) |
| 3964 |
for t in target.link_depends]) |
| 3965 |
elem = NinjaBuildElement(self.all_outputs, outname, linker_rule, obj_list, implicit_outs=implicit_outs) |
| 3966 |
all_deps = [*dep_targets, *extra_objs, *custom_target_libraries] |
| 3967 |
elem.add_dep(all_deps) |
| 3968 |
if linker.get_id() == 'tasking': |
| 3969 |
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)): |
| 3970 |
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.') |
| 3971 |
|
| 3972 |
# Compiler args must be included in TI C28x linker commands. |
| 3973 |
compile_args: T.List[str] = [] |
| 3974 |
if linker.get_id() in {'c2000', 'c6000', 'ti'}: |
| 3975 |
for for_machine in MachineChoice: |
| 3976 |
clist = self.environment.coredata.compilers[for_machine] |
| 3977 |
for langname, compiler in clist.items(): |
| 3978 |
if langname in {'c', 'cpp'} and compiler.get_id() in {'c2000', 'c6000', 'ti'}: |
| 3979 |
compile_args += self.generate_basic_compiler_args(target, compiler) |
| 3980 |
|
| 3981 |
# Add early arguments before any object files or libraries |
| 3982 |
if not isinstance(target, build.StaticLibrary): |
| 3983 |
assert isinstance(linker, Compiler) |
| 3984 |
compile_args += linker.get_target_link_early_args(target) |
| 3985 |
if compile_args: |
| 3986 |
elem.add_item('ARGS', compile_args) |
| 3987 |
elem.add_item('LINK_ARGS', commands) |
| 3988 |
self.create_target_linker_introspection(target, linker, commands) |
| 3989 |
return elem |
| 3990 |
|
| 3991 |
def get_import_std_object(self, target: build.BuildTarget) -> T.List[str]: |
| 3992 |
if not self.target_uses_import_std(target): |
| 3993 |
return [] |
| 3994 |
return self.import_std.gen_objects |
| 3995 |
|
| 3996 |
def get_dependency_filename(self, t: T.Union[File, build.BuildTargetTypes]) -> str: |
| 3997 |
if isinstance(t, build.SharedLibrary): |
| 3998 |
if t.uses_rust() and t.rust_crate_type == 'proc-macro': |
| 3999 |
return self.get_target_filename(t) |
| 4000 |
else: |
| 4001 |
return self.get_target_shsym_filename(t) |
| 4002 |
elif isinstance(t, mesonlib.File): |
| 4003 |
if t.is_built: |
| 4004 |
return t.relative_name() |
| 4005 |
else: |
| 4006 |
return t.absolute_path(self.environment.get_source_dir(), |
| 4007 |
self.environment.get_build_dir()) |
| 4008 |
return self.get_target_filename(t) |
| 4009 |
|
| 4010 |
def generate_shlib_aliases(self, target: build.BuildTarget, outdir: str) -> None: |
| 4011 |
for alias, to, tag in target.get_aliases(): |
| 4012 |
aliasfile = os.path.join(outdir, alias) |
| 4013 |
abs_aliasfile = os.path.join(self.environment.get_build_dir(), outdir, alias) |
| 4014 |
try: |
| 4015 |
os.remove(abs_aliasfile) |
| 4016 |
except Exception: |
| 4017 |
pass |
| 4018 |
try: |
| 4019 |
os.symlink(to, abs_aliasfile) |
| 4020 |
except NotImplementedError: |
| 4021 |
mlog.debug("Library versioning disabled because symlinks are not supported.") |
| 4022 |
except OSError: |
| 4023 |
mlog.debug("Library versioning disabled because we do not have symlink creation privileges.") |
| 4024 |
else: |
| 4025 |
self.implicit_meson_outs.append(aliasfile) |
| 4026 |
|
| 4027 |
def generate_custom_target_clean(self, trees: T.List[str]) -> str: |
| 4028 |
e = self.create_phony_target('clean-ctlist', 'CUSTOM_COMMAND', 'PHONY') |
| 4029 |
d = CleanTrees(self.environment.get_build_dir(), trees) |
| 4030 |
d_file = os.path.join(self.environment.get_scratch_dir(), 'cleantrees.dat') |
| 4031 |
e.add_item('COMMAND', self.environment.get_build_command() + ['--internal', 'cleantrees', d_file]) |
| 4032 |
e.add_item('description', 'Cleaning custom target directories') |
| 4033 |
self.add_build(e) |
| 4034 |
# Write out the data file passed to the script |
| 4035 |
with open(d_file, 'wb') as ofile: |
| 4036 |
pickle.dump(d, ofile) |
| 4037 |
return 'clean-ctlist' |
| 4038 |
|
| 4039 |
def generate_gcov_clean(self) -> None: |
| 4040 |
gcno_elem = self.create_phony_target('clean-gcno', 'CUSTOM_COMMAND', 'PHONY') |
| 4041 |
gcno_elem.add_item('COMMAND', mesonlib.get_meson_command() + ['--internal', 'delwithsuffix', '.', 'gcno']) |
| 4042 |
gcno_elem.add_item('description', 'Deleting gcno files') |
| 4043 |
self.add_build(gcno_elem) |
| 4044 |
|
| 4045 |
gcda_elem = self.create_phony_target('clean-gcda', 'CUSTOM_COMMAND', 'PHONY') |
| 4046 |
gcda_elem.add_item('COMMAND', mesonlib.get_meson_command() + ['--internal', 'delwithsuffix', '.', 'gcda']) |
| 4047 |
gcda_elem.add_item('description', 'Deleting gcda files') |
| 4048 |
self.add_build(gcda_elem) |
| 4049 |
|
| 4050 |
def get_user_option_args(self) -> T.List[str]: |
| 4051 |
cmds = [] |
| 4052 |
for k, v in self.environment.coredata.optstore.items(): |
| 4053 |
if self.environment.coredata.optstore.is_project_option(k): |
| 4054 |
cmds.append('-D' + str(k) + '=' + (v.value if isinstance(v.value, str) else str(v.value).lower())) |
| 4055 |
# The order of these arguments must be the same between runs of Meson |
| 4056 |
# to ensure reproducible output. The order we pass them shouldn't |
| 4057 |
# affect behavior in any other way. |
| 4058 |
return sorted(cmds) |
| 4059 |
|
| 4060 |
def generate_dist(self) -> None: |
| 4061 |
elem = self.create_phony_target('dist', 'CUSTOM_COMMAND', 'PHONY') |
| 4062 |
elem.add_item('DESC', 'Creating source packages') |
| 4063 |
elem.add_item('COMMAND', self.environment.get_build_command() + ['dist']) |
| 4064 |
elem.add_item('pool', 'console') |
| 4065 |
self.add_build(elem) |
| 4066 |
|
| 4067 |
def generate_clippy(self) -> None: |
| 4068 |
if 'clippy' in self.all_outputs or not self.have_language('rust'): |
| 4069 |
return |
| 4070 |
|
| 4071 |
cmd = self.environment.get_build_command() + \ |
| 4072 |
['--internal', 'clippy', self.environment.build_dir] |
| 4073 |
elem = self.create_phony_target('clippy', 'CUSTOM_COMMAND', 'PHONY') |
| 4074 |
elem.add_item('COMMAND', cmd) |
| 4075 |
elem.add_item('pool', 'console') |
| 4076 |
for crate in self.rust_crates.values(): |
| 4077 |
if crate.crate_type in {'rlib', 'dylib', 'proc-macro'}: |
| 4078 |
elem.add_dep(crate.target_name) |
| 4079 |
elem.add_dep(list(self.all_structured_sources)) |
| 4080 |
self.add_build(elem) |
| 4081 |
|
| 4082 |
def generate_clippy_json_prereq(self) -> None: |
| 4083 |
if 'clippy-json-prereq' in self.all_outputs or not self.have_language('rust'): |
| 4084 |
return |
| 4085 |
|
| 4086 |
elem = self.create_phony_target('clippy-json-prereq', 'CUSTOM_COMMAND', 'PHONY') |
| 4087 |
for crate in self.rust_crates.values(): |
| 4088 |
if crate.crate_type in {'rlib', 'dylib', 'proc-macro'}: |
| 4089 |
elem.add_dep(crate.target_name) |
| 4090 |
elem.add_dep(list(self.all_structured_sources)) |
| 4091 |
self.add_build(elem) |
| 4092 |
|
| 4093 |
def generate_clippy_json(self) -> None: |
| 4094 |
if 'clippy-json' in self.all_outputs or not self.have_language('rust'): |
| 4095 |
return |
| 4096 |
|
| 4097 |
cmd = self.environment.get_build_command() + \ |
| 4098 |
['--internal', 'clippy', self.environment.build_dir, '--error-format=json'] |
| 4099 |
elem = self.create_phony_target('clippy-json', 'CUSTOM_COMMAND', 'PHONY') |
| 4100 |
elem.add_item('COMMAND', cmd) |
| 4101 |
elem.add_item('pool', 'console') |
| 4102 |
self.add_build(elem) |
| 4103 |
|
| 4104 |
def generate_rustdoc(self) -> None: |
| 4105 |
if 'rustdoc' in self.all_outputs or not self.have_language('rust'): |
| 4106 |
return |
| 4107 |
|
| 4108 |
cmd = self.environment.get_build_command() + \ |
| 4109 |
['--internal', 'rustdoc', self.environment.build_dir] |
| 4110 |
elem = self.create_phony_target('rustdoc', 'CUSTOM_COMMAND', 'PHONY') |
| 4111 |
elem.add_item('COMMAND', cmd) |
| 4112 |
elem.add_item('pool', 'console') |
| 4113 |
for crate in self.rust_crates.values(): |
| 4114 |
if crate.crate_type in {'rlib', 'dylib', 'proc-macro'}: |
| 4115 |
elem.add_dep(crate.target_name) |
| 4116 |
elem.add_dep(list(self.all_structured_sources)) |
| 4117 |
self.add_build(elem) |
| 4118 |
|
| 4119 |
def generate_scanbuild(self) -> None: |
| 4120 |
if not tooldetect.detect_scanbuild(): |
| 4121 |
return |
| 4122 |
if 'scan-build' in self.all_outputs: |
| 4123 |
return |
| 4124 |
cmd = self.environment.get_build_command() + \ |
| 4125 |
['--internal', 'scanbuild', self.environment.source_dir, self.environment.build_dir, self.build.get_subproject_dir()] + \ |
| 4126 |
self.environment.get_build_command() + ['setup'] + self.get_user_option_args() |
| 4127 |
elem = self.create_phony_target('scan-build', 'CUSTOM_COMMAND', 'PHONY') |
| 4128 |
elem.add_item('COMMAND', cmd) |
| 4129 |
elem.add_item('pool', 'console') |
| 4130 |
self.add_build(elem) |
| 4131 |
|
| 4132 |
def generate_clangtool(self, name: str, extra_arg: T.Optional[str] = None, need_pch: bool = False) -> None: |
| 4133 |
target_name = 'clang-' + name |
| 4134 |
extra_args = [] |
| 4135 |
if extra_arg: |
| 4136 |
target_name += f'-{extra_arg}' |
| 4137 |
extra_args.append(f'--{extra_arg}') |
| 4138 |
colorout = self.environment.coredata.optstore.get_value_for('b_colorout') \ |
| 4139 |
if OptionKey('b_colorout') in self.environment.coredata.optstore else 'always' |
| 4140 |
assert isinstance(colorout, str), 'for mypy' |
| 4141 |
extra_args.extend(['--color', colorout]) |
| 4142 |
if not os.path.exists(os.path.join(self.environment.source_dir, '.clang-' + name)) and \ |
| 4143 |
not os.path.exists(os.path.join(self.environment.source_dir, '_clang-' + name)): |
| 4144 |
return |
| 4145 |
if target_name in self.all_outputs: |
| 4146 |
return |
| 4147 |
if need_pch and not set(self.all_pch.keys()) <= {'clang'}: |
| 4148 |
return |
| 4149 |
|
| 4150 |
cmd = self.environment.get_build_command() + \ |
| 4151 |
['--internal', 'clang' + name, self.environment.source_dir, self.environment.build_dir] + \ |
| 4152 |
extra_args |
| 4153 |
elem = self.create_phony_target(target_name, 'CUSTOM_COMMAND', 'PHONY') |
| 4154 |
elem.add_item('COMMAND', cmd) |
| 4155 |
elem.add_item('pool', 'console') |
| 4156 |
if need_pch: |
| 4157 |
elem.add_dep(list(self.all_pch['clang'])) |
| 4158 |
self.add_build(elem) |
| 4159 |
|
| 4160 |
def generate_clangformat(self) -> None: |
| 4161 |
if not tooldetect.detect_clangformat(): |
| 4162 |
return |
| 4163 |
self.generate_clangtool('format') |
| 4164 |
self.generate_clangtool('format', 'check') |
| 4165 |
|
| 4166 |
def generate_clangtidy(self) -> None: |
| 4167 |
if not tooldetect.detect_clangtidy(): |
| 4168 |
return |
| 4169 |
self.generate_clangtool('tidy', need_pch=True) |
| 4170 |
if not tooldetect.detect_clangapply(): |
| 4171 |
return |
| 4172 |
self.generate_clangtool('tidy', 'fix', need_pch=True) |
| 4173 |
|
| 4174 |
def generate_tags(self, tool: str, target_name: str) -> None: |
| 4175 |
import shutil |
| 4176 |
if not shutil.which(tool): |
| 4177 |
return |
| 4178 |
if target_name in self.all_outputs: |
| 4179 |
return |
| 4180 |
cmd = self.environment.get_build_command() + \ |
| 4181 |
['--internal', 'tags', tool, self.environment.source_dir] |
| 4182 |
elem = self.create_phony_target(target_name, 'CUSTOM_COMMAND', 'PHONY') |
| 4183 |
elem.add_item('COMMAND', cmd) |
| 4184 |
elem.add_item('pool', 'console') |
| 4185 |
self.add_build(elem) |
| 4186 |
|
| 4187 |
# For things like scan-build and other helper tools we might have. |
| 4188 |
def generate_utils(self) -> None: |
| 4189 |
self.generate_scanbuild() |
| 4190 |
self.generate_clangformat() |
| 4191 |
self.generate_clangtidy() |
| 4192 |
self.generate_clippy() |
| 4193 |
self.generate_clippy_json_prereq() |
| 4194 |
self.generate_clippy_json() |
| 4195 |
self.generate_rustdoc() |
| 4196 |
self.generate_tags('etags', 'TAGS') |
| 4197 |
self.generate_tags('ctags', 'ctags') |
| 4198 |
self.generate_tags('cscope', 'cscope') |
| 4199 |
cmd = self.environment.get_build_command() + ['--internal', 'uninstall'] |
| 4200 |
elem = self.create_phony_target('uninstall', 'CUSTOM_COMMAND', 'PHONY') |
| 4201 |
elem.add_item('COMMAND', cmd) |
| 4202 |
elem.add_item('pool', 'console') |
| 4203 |
self.add_build(elem) |
| 4204 |
|
| 4205 |
def generate_ending(self) -> None: |
| 4206 |
for targ, deps in [ |
| 4207 |
('all', self.get_build_by_default_targets().values()), |
| 4208 |
('meson-test-prereq', self.get_testlike_targets()), |
| 4209 |
('meson-benchmark-prereq', self.get_testlike_targets(True))]: |
| 4210 |
targetlist = [] |
| 4211 |
for t in deps: |
| 4212 |
# Add the first output of each target to the 'all' target so that |
| 4213 |
# they are all built |
| 4214 |
#Add archive file if shared library in AIX for build all. |
| 4215 |
if isinstance(t, build.SharedLibrary) and t.aix_so_archive: |
| 4216 |
if self.environment.machines[t.for_machine].is_aix(): |
| 4217 |
linker, stdlib_args = t.get_clink_dynamic_linker_and_stdlibs() |
| 4218 |
t.get_outputs()[0] = linker.get_archive_name(t.get_outputs()[0]) |
| 4219 |
targetlist.append(os.path.join(self.get_target_dir(t), t.get_outputs()[0])) |
| 4220 |
|
| 4221 |
# Add an import library if shared library in OS/2 for build all |
| 4222 |
if isinstance(t, build.SharedLibrary): |
| 4223 |
if self.environment.machines[t.for_machine].is_os2(): |
| 4224 |
targetlist.append(os.path.join(self.get_target_dir(t), t.import_filename)) |
| 4225 |
|
| 4226 |
elem = NinjaBuildElement(self.all_outputs, targ, 'phony', targetlist) |
| 4227 |
self.add_build(elem) |
| 4228 |
|
| 4229 |
elem = self.create_phony_target('clean', 'CUSTOM_COMMAND', 'PHONY') |
| 4230 |
elem.add_item('COMMAND', self.ninja_command + ['-t', 'clean']) |
| 4231 |
elem.add_item('description', 'Cleaning') |
| 4232 |
|
| 4233 |
# If we have custom targets in this project, add all their outputs to |
| 4234 |
# the list that is passed to the `cleantrees.py` script. The script |
| 4235 |
# will manually delete all custom_target outputs that are directories |
| 4236 |
# instead of files. This is needed because on platforms other than |
| 4237 |
# Windows, Ninja only deletes directories while cleaning if they are |
| 4238 |
# empty. https://github.com/mesonbuild/meson/issues/1220 |
| 4239 |
ctlist = [] |
| 4240 |
for t in self.build.get_targets().values(): |
| 4241 |
if isinstance(t, build.CustomTarget): |
| 4242 |
# Create a list of all custom target outputs |
| 4243 |
for o in t.get_outputs(): |
| 4244 |
ctlist.append(os.path.join(self.get_target_dir(t), o)) |
| 4245 |
# Also clean meson-dist directory created by `meson dist` |
| 4246 |
ctlist.append('meson-dist') |
| 4247 |
if ctlist: |
| 4248 |
elem.add_dep(self.generate_custom_target_clean(ctlist)) |
| 4249 |
|
| 4250 |
if OptionKey('b_coverage') in self.environment.coredata.optstore and \ |
| 4251 |
self.environment.coredata.optstore.get_value_for('b_coverage'): |
| 4252 |
self.generate_gcov_clean() |
| 4253 |
elem.add_dep('clean-gcda') |
| 4254 |
elem.add_dep('clean-gcno') |
| 4255 |
self.add_build(elem) |
| 4256 |
|
| 4257 |
deps = self.get_regen_filelist() |
| 4258 |
elem = NinjaBuildElement(self.all_outputs, 'build.ninja', 'REGENERATE_BUILD', deps) |
| 4259 |
elem.add_item('pool', 'console') |
| 4260 |
self.add_build(elem) |
| 4261 |
|
| 4262 |
# If these files used to be explicitly created, they need to appear on the build graph somehow, |
| 4263 |
# otherwise cleandead deletes them. See https://github.com/ninja-build/ninja/issues/2299 |
| 4264 |
if self.implicit_meson_outs: |
| 4265 |
elem = NinjaBuildElement(self.all_outputs, 'meson-implicit-outs', 'phony', self.implicit_meson_outs) |
| 4266 |
self.add_build(elem) |
| 4267 |
|
| 4268 |
elem = NinjaBuildElement(self.all_outputs, 'reconfigure', 'REGENERATE_BUILD', 'PHONY') |
| 4269 |
elem.add_item('pool', 'console') |
| 4270 |
self.add_build(elem) |
| 4271 |
|
| 4272 |
elem = NinjaBuildElement(self.all_outputs, deps, 'phony', '') |
| 4273 |
self.add_build(elem) |
| 4274 |
|
| 4275 |
def get_introspection_data(self, target_id: str, target: build.Target) -> T.List[TargetIntrospectionData]: |
| 4276 |
data = self.introspection_data.get(target_id) |
| 4277 |
if not data: |
| 4278 |
return super().get_introspection_data(target_id, target) |
| 4279 |
|
| 4280 |
return list(data.values()) |
| 4281 |
|
| 4282 |
|
| 4283 |
def _scan_fortran_file_deps(src: Path, srcdir: Path, dirname: Path, tdeps: T.Dict[str, File], compiler: FortranCompiler) -> T.List[str]: |
| 4284 |
""" |
| 4285 |
scan a Fortran file for dependencies. Needs to be distinct from target |
| 4286 |
to allow for recursion induced by `include` statements.er |
| 4287 |
|
| 4288 |
It makes a number of assumptions, including |
| 4289 |
|
| 4290 |
* `use`, `module`, `submodule` name is not on a continuation line |
| 4291 |
|
| 4292 |
Regex |
| 4293 |
----- |
| 4294 |
|
| 4295 |
* `incre` works for `#include "foo.f90"` and `include "foo.f90"` |
| 4296 |
* `usere` works for legacy and Fortran 2003 `use` statements |
| 4297 |
* `submodre` is for Fortran >= 2008 `submodule` |
| 4298 |
""" |
| 4299 |
|
| 4300 |
incre = re.compile(FORTRAN_INCLUDE_PAT, re.IGNORECASE) |
| 4301 |
usere = re.compile(FORTRAN_USE_PAT, re.IGNORECASE) |
| 4302 |
submodre = re.compile(FORTRAN_SUBMOD_PAT, re.IGNORECASE) |
| 4303 |
|
| 4304 |
mod_files = [] |
| 4305 |
src = Path(src) |
| 4306 |
with src.open(encoding='ascii', errors='ignore') as f: |
| 4307 |
for line in f: |
| 4308 |
# included files |
| 4309 |
incmatch = incre.match(line) |
| 4310 |
if incmatch is not None: |
| 4311 |
incfile = src.parent / incmatch.group(1) |
| 4312 |
# NOTE: src.parent is most general, in particular for CMake subproject with Fortran file |
| 4313 |
# having an `include 'foo.f'` statement. |
| 4314 |
if incfile.suffix.lower()[1:] in compiler.file_suffixes: |
| 4315 |
mod_files.extend(_scan_fortran_file_deps(incfile, srcdir, dirname, tdeps, compiler)) |
| 4316 |
# modules |
| 4317 |
usematch = usere.match(line) |
| 4318 |
if usematch is not None: |
| 4319 |
usename = usematch.group(1).lower() |
| 4320 |
if usename == 'intrinsic': # this keeps the regex simpler |
| 4321 |
continue |
| 4322 |
if usename not in tdeps: |
| 4323 |
# The module is not provided by any source file. This |
| 4324 |
# is due to: |
| 4325 |
# a) missing file/typo/etc |
| 4326 |
# b) using a module provided by the compiler, such as |
| 4327 |
# OpenMP |
| 4328 |
# There's no easy way to tell which is which (that I |
| 4329 |
# know of) so just ignore this and go on. Ideally we |
| 4330 |
# would print a warning message to the user but this is |
| 4331 |
# a common occurrence, which would lead to lots of |
| 4332 |
# distracting noise. |
| 4333 |
continue |
| 4334 |
srcfile = srcdir / tdeps[usename].fname |
| 4335 |
if not srcfile.is_file(): |
| 4336 |
if srcfile.name != src.name: # generated source file |
| 4337 |
pass |
| 4338 |
else: # subproject |
| 4339 |
continue |
| 4340 |
elif srcfile.samefile(src): # self-reference |
| 4341 |
continue |
| 4342 |
|
| 4343 |
mod_name = compiler.module_name_to_filename(usename) |
| 4344 |
mod_files.append(str(dirname / mod_name)) |
| 4345 |
else: # submodules |
| 4346 |
submodmatch = submodre.match(line) |
| 4347 |
if submodmatch is not None: |
| 4348 |
parents = submodmatch.group(1).lower().split(':') |
| 4349 |
assert len(parents) in {1, 2}, ( |
| 4350 |
'submodule ancestry must be specified as' |
| 4351 |
f' ancestor:parent but Meson found {parents}') |
| 4352 |
|
| 4353 |
ancestor_child = '_'.join(parents) |
| 4354 |
if ancestor_child not in tdeps: |
| 4355 |
raise MesonException("submodule {} relies on ancestor module {} that was not found.".format(submodmatch.group(2).lower(), ancestor_child.split('_', maxsplit=1)[0])) |
| 4356 |
submodsrcfile = srcdir / tdeps[ancestor_child].fname |
| 4357 |
if not submodsrcfile.is_file(): |
| 4358 |
if submodsrcfile.name != src.name: # generated source file |
| 4359 |
pass |
| 4360 |
else: # subproject |
| 4361 |
continue |
| 4362 |
elif submodsrcfile.samefile(src): # self-reference |
| 4363 |
continue |
| 4364 |
mod_name = compiler.module_name_to_filename(ancestor_child) |
| 4365 |
mod_files.append(str(dirname / mod_name)) |
| 4366 |
return mod_files |