From 09b53c534f74806ebc49bb2fcdfbae0e3b26fb84 Mon Sep 17 00:00:00 2001 From: Daniel Mensinger Date: Mon, 6 Jan 2020 15:27:38 +0100 Subject: types: import typing as T (fixes #6333) --- mesonbuild/ast/interpreter.py | 10 +- mesonbuild/backend/backends.py | 14 +- mesonbuild/backend/ninjabackend.py | 6 +- mesonbuild/build.py | 30 +-- mesonbuild/cmake/client.py | 14 +- mesonbuild/cmake/common.py | 4 +- mesonbuild/cmake/executor.py | 18 +- mesonbuild/cmake/fileapi.py | 14 +- mesonbuild/cmake/interpreter.py | 62 +++--- mesonbuild/cmake/traceparser.py | 28 +-- mesonbuild/compilers/c.py | 6 +- mesonbuild/compilers/compilers.py | 138 ++++++------ mesonbuild/compilers/cpp.py | 8 +- mesonbuild/compilers/cs.py | 4 +- mesonbuild/compilers/cuda.py | 16 +- mesonbuild/compilers/d.py | 10 +- mesonbuild/compilers/fortran.py | 18 +- mesonbuild/compilers/java.py | 4 +- mesonbuild/compilers/mixins/arm.py | 50 ++--- mesonbuild/compilers/mixins/ccrx.py | 32 +-- mesonbuild/compilers/mixins/clang.py | 20 +- mesonbuild/compilers/mixins/clike.py | 28 +-- mesonbuild/compilers/mixins/elbrus.py | 12 +- mesonbuild/compilers/mixins/emscripten.py | 6 +- mesonbuild/compilers/mixins/gnu.py | 76 +++---- mesonbuild/compilers/mixins/intel.py | 32 +-- mesonbuild/compilers/mixins/islinker.py | 52 ++--- mesonbuild/compilers/mixins/pgi.py | 28 +-- mesonbuild/compilers/mixins/visualstudio.py | 82 ++++---- mesonbuild/compilers/objc.py | 6 +- mesonbuild/compilers/objcpp.py | 6 +- mesonbuild/compilers/rust.py | 4 +- mesonbuild/compilers/swift.py | 4 +- mesonbuild/compilers/vala.py | 4 +- mesonbuild/coredata.py | 99 +++++---- mesonbuild/dependencies/base.py | 64 +++--- mesonbuild/dependencies/dev.py | 6 +- mesonbuild/dependencies/mpi.py | 10 +- mesonbuild/envconfig.py | 64 +++--- mesonbuild/environment.py | 25 +-- mesonbuild/interpreter.py | 16 +- mesonbuild/linkers.py | 312 ++++++++++++++-------------- mesonbuild/mesonlib.py | 66 +++--- mesonbuild/mintro.py | 88 ++++---- mesonbuild/mlog.py | 67 +++--- mesonbuild/modules/fs.py | 26 +-- mesonbuild/modules/python.py | 8 +- mesonbuild/msetup.py | 6 +- mesonbuild/mtest.py | 84 ++++---- mesonbuild/optinterpreter.py | 4 +- mesonbuild/rewriter.py | 30 +-- mesonbuild/wrap/wrap.py | 10 +- 52 files changed, 909 insertions(+), 922 deletions(-) (limited to 'mesonbuild') diff --git a/mesonbuild/ast/interpreter.py b/mesonbuild/ast/interpreter.py index ebdde3f..b5aade3 100644 --- a/mesonbuild/ast/interpreter.py +++ b/mesonbuild/ast/interpreter.py @@ -35,7 +35,7 @@ from ..mparser import ( ) import os, sys -from typing import List, Any, Optional +import typing as T class DontCareObject(interpreterbase.InterpreterObject): pass @@ -59,7 +59,7 @@ ADD_SOURCE = 0 REMOVE_SOURCE = 1 class AstInterpreter(interpreterbase.InterpreterBase): - def __init__(self, source_root: str, subdir: str, visitors: Optional[List[AstVisitor]] = None): + def __init__(self, source_root: str, subdir: str, visitors: T.Optional[T.List[AstVisitor]] = None): super().__init__(source_root, subdir) self.visitors = visitors if visitors is not None else [] self.visited_subdirs = {} @@ -246,8 +246,8 @@ class AstInterpreter(interpreterbase.InterpreterBase): self.reverse_assignment[node.value.ast_id] = node self.assign_vals[node.var_name] = [self.evaluate_statement(node.value)] # Evaluate the value just in case - def resolve_node(self, node: BaseNode, include_unknown_args: bool = False, id_loop_detect: Optional[List[str]] = None) -> Optional[Any]: - def quick_resolve(n: BaseNode, loop_detect: Optional[List[str]] = None) -> Any: + def resolve_node(self, node: BaseNode, include_unknown_args: bool = False, id_loop_detect: T.Optional[T.List[str]] = None) -> T.Optional[T.Any]: + def quick_resolve(n: BaseNode, loop_detect: T.Optional[T.List[str]] = None) -> T.Any: if loop_detect is None: loop_detect = [] if isinstance(n, IdNode): @@ -327,7 +327,7 @@ class AstInterpreter(interpreterbase.InterpreterBase): return result - def flatten_args(self, args: Any, include_unknown_args: bool = False, id_loop_detect: Optional[List[str]] = None) -> List[Any]: + def flatten_args(self, args: T.Any, include_unknown_args: bool = False, id_loop_detect: T.Optional[T.List[str]] = None) -> T.List[T.Any]: # Make sure we are always dealing with lists if not isinstance(args, list): args = [args] diff --git a/mesonbuild/backend/backends.py b/mesonbuild/backend/backends.py index e548096..2a07058 100644 --- a/mesonbuild/backend/backends.py +++ b/mesonbuild/backend/backends.py @@ -27,7 +27,7 @@ from ..compilers import CompilerArgs, VisualStudioLikeCompiler from collections import OrderedDict import shlex from functools import lru_cache -import typing +import typing as T class CleanTrees: @@ -81,12 +81,12 @@ class ExecutableSerialisation: self.capture = capture class TestSerialisation: - def __init__(self, name: str, project: str, suite: str, fname: typing.List[str], - is_cross_built: bool, exe_wrapper: typing.Optional[build.Executable], - needs_exe_wrapper: bool, is_parallel: bool, cmd_args: typing.List[str], + def __init__(self, name: str, project: str, suite: str, fname: T.List[str], + is_cross_built: bool, exe_wrapper: T.Optional[build.Executable], + needs_exe_wrapper: bool, is_parallel: bool, cmd_args: T.List[str], env: build.EnvironmentVariables, should_fail: bool, - timeout: typing.Optional[int], workdir: typing.Optional[str], - extra_paths: typing.List[str], protocol: str, priority: int): + timeout: T.Optional[int], workdir: T.Optional[str], + extra_paths: T.List[str], protocol: str, priority: int): self.name = name self.project_name = project self.suite = suite @@ -676,7 +676,7 @@ class Backend: paths.update(cc.get_library_dirs(self.environment)) return list(paths) - def determine_windows_extra_paths(self, target: typing.Union[build.BuildTarget, str], extra_bdeps): + def determine_windows_extra_paths(self, target: T.Union[build.BuildTarget, str], extra_bdeps): '''On Windows there is no such thing as an rpath. We must determine all locations of DLLs that this exe links to and return them so they can be used in unit diff --git a/mesonbuild/backend/ninjabackend.py b/mesonbuild/backend/ninjabackend.py index 824b958..31a7a43 100644 --- a/mesonbuild/backend/ninjabackend.py +++ b/mesonbuild/backend/ninjabackend.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -from typing import List +import typing as T import os import re import pickle @@ -1872,7 +1872,7 @@ https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47485''')) self.fortran_deps[target.get_basename()] = {**module_files, **submodule_files} - def get_fortran_deps(self, compiler: FortranCompiler, src: Path, target) -> List[str]: + def get_fortran_deps(self, compiler: FortranCompiler, src: Path, target) -> T.List[str]: """ Find all module and submodule needed by a Fortran target """ @@ -2795,7 +2795,7 @@ def load(build_dir): return obj -def _scan_fortran_file_deps(src: Path, srcdir: Path, dirname: Path, tdeps, compiler) -> List[str]: +def _scan_fortran_file_deps(src: Path, srcdir: Path, dirname: Path, tdeps, compiler) -> T.List[str]: """ scan a Fortran file for dependencies. Needs to be distinct from target to allow for recursion induced by `include` statements.er diff --git a/mesonbuild/build.py b/mesonbuild/build.py index 645db24..72b4276 100644 --- a/mesonbuild/build.py +++ b/mesonbuild/build.py @@ -18,7 +18,7 @@ import itertools, pathlib import hashlib import pickle from functools import lru_cache -import typing +import typing as T from . import environment from . import dependencies @@ -117,11 +117,11 @@ class Build: self.environment = environment self.projects = {} self.targets = OrderedDict() - self.run_target_names = set() # type: typing.Set[typing.Tuple[str, str]] - self.global_args = PerMachine({}, {}) # type: PerMachine[typing.Dict[str, typing.List[str]]] - self.projects_args = PerMachine({}, {}) # type: PerMachine[typing.Dict[str, typing.List[str]]] - self.global_link_args = PerMachine({}, {}) # type: PerMachine[typing.Dict[str, typing.List[str]]] - self.projects_link_args = PerMachine({}, {}) # type: PerMachine[typing.Dict[str, typing.List[str]]] + self.run_target_names = set() # type: T.Set[T.Tuple[str, str]] + self.global_args = PerMachine({}, {}) # type: PerMachine[T.Dict[str, T.List[str]]] + self.projects_args = PerMachine({}, {}) # type: PerMachine[T.Dict[str, T.List[str]]] + self.global_link_args = PerMachine({}, {}) # type: PerMachine[T.Dict[str, T.List[str]]] + self.projects_link_args = PerMachine({}, {}) # type: PerMachine[T.Dict[str, T.List[str]]] self.tests = [] self.benchmarks = [] self.headers = [] @@ -137,7 +137,7 @@ class Build: self.dep_manifest_name = None self.dep_manifest = {} self.stdlibs = PerMachine({}, {}) - self.test_setups = {} # type: typing.Dict[str, TestSetup] + self.test_setups = {} # type: T.Dict[str, TestSetup] self.test_setup_default_name = None self.find_overrides = {} self.searched_programs = set() # The list of all programs that have been searched for. @@ -331,7 +331,7 @@ class EnvironmentVariables: return value - def get_env(self, full_env: typing.Dict[str, str]) -> typing.Dict[str, str]: + def get_env(self, full_env: T.Dict[str, str]) -> T.Dict[str, str]: env = full_env.copy() for method, name, values, kwargs in self.envvars: env[name] = method(full_env, name, values, kwargs) @@ -355,22 +355,22 @@ a hard error in the future.''' % name) if not hasattr(self, 'typename'): raise RuntimeError('Target type is not set for target class "{}". This is a bug'.format(type(self).__name__)) - def __lt__(self, other: typing.Any) -> typing.Union[bool, 'NotImplemented']: + def __lt__(self, other: T.Any) -> T.Union[bool, 'NotImplemented']: if not hasattr(other, 'get_id') and not callable(other.get_id): return NotImplemented return self.get_id() < other.get_id() - def __le__(self, other: typing.Any) -> typing.Union[bool, 'NotImplemented']: + def __le__(self, other: T.Any) -> T.Union[bool, 'NotImplemented']: if not hasattr(other, 'get_id') and not callable(other.get_id): return NotImplemented return self.get_id() <= other.get_id() - def __gt__(self, other: typing.Any) -> typing.Union[bool, 'NotImplemented']: + def __gt__(self, other: T.Any) -> T.Union[bool, 'NotImplemented']: if not hasattr(other, 'get_id') and not callable(other.get_id): return NotImplemented return self.get_id() > other.get_id() - def __ge__(self, other: typing.Any) -> typing.Union[bool, 'NotImplemented']: + def __ge__(self, other: T.Any) -> T.Union[bool, 'NotImplemented']: if not hasattr(other, 'get_id') and not callable(other.get_id): return NotImplemented return self.get_id() >= other.get_id() @@ -1171,7 +1171,7 @@ You probably should put it in link_with instead.''') raise MesonException('File %s does not exist.' % f) self.pch[language] = pchlist - def add_include_dirs(self, args, set_is_system: typing.Optional[str] = None): + def add_include_dirs(self, args, set_is_system: T.Optional[str] = None): ids = [] for a in args: # FIXME same hack, forcibly unpack from holder. @@ -1200,7 +1200,7 @@ You probably should put it in link_with instead.''') def get_aliases(self): return {} - def get_langs_used_by_deps(self) -> typing.List[str]: + def get_langs_used_by_deps(self) -> T.List[str]: ''' Sometimes you want to link to a C++ library that exports C API, which means the linker must link in the C++ stdlib, and we must use a C++ @@ -2448,7 +2448,7 @@ class RunScript(dict): self['args'] = args class TestSetup: - def __init__(self, exe_wrapper: typing.Optional[typing.List[str]], gdb: bool, + def __init__(self, exe_wrapper: T.Optional[T.List[str]], gdb: bool, timeout_multiplier: int, env: EnvironmentVariables): self.exe_wrapper = exe_wrapper self.gdb = gdb diff --git a/mesonbuild/cmake/client.py b/mesonbuild/cmake/client.py index 9cb7f74..b88a673 100644 --- a/mesonbuild/cmake/client.py +++ b/mesonbuild/cmake/client.py @@ -22,7 +22,7 @@ from ..mesonlib import MachineChoice from .. import mlog from contextlib import contextmanager from subprocess import Popen, PIPE, TimeoutExpired -from typing import List, Optional +import typing as T import json import os @@ -110,11 +110,11 @@ class Progress(MessageBase): pass class MessageHello(MessageBase): - def __init__(self, supported_protocol_versions: List[dict]): + def __init__(self, supported_protocol_versions: T.List[dict]): super().__init__('hello', '') self.supported_protocol_versions = supported_protocol_versions - def supports(self, major: int, minor: Optional[int] = None) -> bool: + def supports(self, major: int, minor: T.Optional[int] = None) -> bool: for i in self.supported_protocol_versions: if major == i['major']: if minor is None or minor == i['minor']: @@ -124,7 +124,7 @@ class MessageHello(MessageBase): # Request classes class RequestHandShake(RequestBase): - def __init__(self, src_dir: str, build_dir: str, generator: str, vers_major: int, vers_minor: Optional[int] = None): + def __init__(self, src_dir: str, build_dir: str, generator: str, vers_major: int, vers_minor: T.Optional[int] = None): super().__init__('handshake') self.src_dir = src_dir self.build_dir = build_dir @@ -150,7 +150,7 @@ class RequestHandShake(RequestBase): } class RequestConfigure(RequestBase): - def __init__(self, args: Optional[List[str]] = None): + def __init__(self, args: T.Optional[T.List[str]] = None): super().__init__('configure') self.args = args @@ -187,7 +187,7 @@ class ReplyCompute(ReplyBase): super().__init__(cookie, 'compute') class ReplyCMakeInputs(ReplyBase): - def __init__(self, cookie: str, cmake_root: str, src_dir: str, build_files: List[CMakeBuildFile]): + def __init__(self, cookie: str, cmake_root: str, src_dir: str, build_files: T.List[CMakeBuildFile]): super().__init__(cookie, 'cmakeInputs') self.cmake_root = cmake_root self.src_dir = src_dir @@ -296,7 +296,7 @@ class CMakeClient: raise CMakeException('CMake server query failed') return reply - def do_handshake(self, src_dir: str, build_dir: str, generator: str, vers_major: int, vers_minor: Optional[int] = None) -> None: + def do_handshake(self, src_dir: str, build_dir: str, generator: str, vers_major: int, vers_minor: T.Optional[int] = None) -> None: # CMake prints the hello message on startup msg = self.readMessage() if not isinstance(msg, MessageHello): diff --git a/mesonbuild/cmake/common.py b/mesonbuild/cmake/common.py index 7a0e784..e7da0d7 100644 --- a/mesonbuild/cmake/common.py +++ b/mesonbuild/cmake/common.py @@ -17,7 +17,7 @@ from ..mesonlib import MesonException from .. import mlog -from typing import List +import typing as T class CMakeException(MesonException): pass @@ -31,7 +31,7 @@ class CMakeBuildFile: def __repr__(self): return '<{}: {}; cmake={}; temp={}>'.format(self.__class__.__name__, self.file, self.is_cmake, self.is_temp) -def _flags_to_list(raw: str) -> List[str]: +def _flags_to_list(raw: str) -> T.List[str]: # Convert a raw commandline string into a list of strings res = [] curr = '' diff --git a/mesonbuild/cmake/executor.py b/mesonbuild/cmake/executor.py index 4300656..bf4fa5d 100644 --- a/mesonbuild/cmake/executor.py +++ b/mesonbuild/cmake/executor.py @@ -17,7 +17,7 @@ import subprocess from pathlib import Path -from typing import List, Tuple, Optional, TYPE_CHECKING +import typing as T import re import os import shutil @@ -27,7 +27,7 @@ from .. import mlog, mesonlib from ..mesonlib import PerMachine, Popen_safe, version_compare, MachineChoice from ..environment import Environment -if TYPE_CHECKING: +if T.TYPE_CHECKING: from ..dependencies.base import ExternalProgram @@ -55,7 +55,7 @@ class CMakeExecutor: self.cmakebin = None return - def find_cmake_binary(self, environment: Environment, silent: bool = False) -> Tuple['ExternalProgram', str]: + def find_cmake_binary(self, environment: Environment, silent: bool = False) -> T.Tuple['ExternalProgram', str]: from ..dependencies.base import ExternalProgram # Create an iterator of options @@ -107,7 +107,7 @@ class CMakeExecutor: return CMakeExecutor.class_cmakebin[self.for_machine], CMakeExecutor.class_cmakevers[self.for_machine] - def check_cmake(self, cmakebin: 'ExternalProgram') -> Optional[str]: + def check_cmake(self, cmakebin: 'ExternalProgram') -> T.Optional[str]: if not cmakebin.found(): mlog.log('Did not find CMake {!r}'.format(cmakebin.name)) return None @@ -130,12 +130,12 @@ class CMakeExecutor: cmvers = re.sub(r'\s*cmake version\s*', '', out.split('\n')[0]).strip() return cmvers - def _cache_key(self, args: List[str], build_dir: str, env): + def _cache_key(self, args: T.List[str], build_dir: str, env): fenv = frozenset(env.items()) if env is not None else None targs = tuple(args) return (self.cmakebin, targs, build_dir, fenv) - def _call_real(self, args: List[str], build_dir: str, env) -> Tuple[int, str, str]: + def _call_real(self, args: T.List[str], build_dir: str, env) -> T.Tuple[int, str, str]: os.makedirs(build_dir, exist_ok=True) cmd = self.cmakebin.get_command() + args ret = subprocess.run(cmd, env=env, cwd=build_dir, close_fds=False, @@ -148,7 +148,7 @@ class CMakeExecutor: mlog.debug("Called `{}` in {} -> {}".format(call, build_dir, rc)) return rc, out, err - def call(self, args: List[str], build_dir: str, env=None, disable_cache: bool = False): + def call(self, args: T.List[str], build_dir: str, env=None, disable_cache: bool = False): if env is None: env = os.environ @@ -162,7 +162,7 @@ class CMakeExecutor: cache[key] = self._call_real(args, build_dir, env) return cache[key] - def call_with_fake_build(self, args: List[str], build_dir: str, env=None): + def call_with_fake_build(self, args: T.List[str], build_dir: str, env=None): # First check the cache cache = CMakeExecutor.class_cmake_cache key = self._cache_key(args, build_dir, env) @@ -186,7 +186,7 @@ class CMakeExecutor: p = fallback return p - def choose_compiler(lang: str) -> Tuple[str, str]: + def choose_compiler(lang: str) -> T.Tuple[str, str]: exe_list = [] if lang in compilers: exe_list = compilers[lang].get_exelist() diff --git a/mesonbuild/cmake/fileapi.py b/mesonbuild/cmake/fileapi.py index c62eadb..f219f16 100644 --- a/mesonbuild/cmake/fileapi.py +++ b/mesonbuild/cmake/fileapi.py @@ -13,7 +13,7 @@ # limitations under the License. from .common import CMakeException, CMakeBuildFile, CMakeConfiguration -from typing import Any, List, Tuple +import typing as T from .. import mlog import os import json @@ -34,10 +34,10 @@ class CMakeFileAPI: 'cmakeFiles': self._parse_cmakeFiles, } - def get_cmake_sources(self) -> List[CMakeBuildFile]: + def get_cmake_sources(self) -> T.List[CMakeBuildFile]: return self.cmake_sources - def get_cmake_configurations(self) -> List[CMakeConfiguration]: + def get_cmake_configurations(self) -> T.List[CMakeConfiguration]: return self.cmake_configurations def setup_request(self) -> None: @@ -100,7 +100,7 @@ class CMakeFileAPI: # resolved and the resulting data structure is identical # to the CMake serve output. - def helper_parse_dir(dir_entry: dict) -> Tuple[str, str]: + def helper_parse_dir(dir_entry: dict) -> T.Tuple[str, str]: src_dir = dir_entry.get('source', '.') bld_dir = dir_entry.get('build', '.') src_dir = src_dir if os.path.isabs(src_dir) else os.path.join(source_dir, src_dir) @@ -110,7 +110,7 @@ class CMakeFileAPI: return src_dir, bld_dir - def parse_sources(comp_group: dict, tgt: dict) -> Tuple[List[str], List[str], List[int]]: + def parse_sources(comp_group: dict, tgt: dict) -> T.Tuple[T.List[str], T.List[str], T.List[int]]: gen = [] src = [] idx = [] @@ -279,7 +279,7 @@ class CMakeFileAPI: path = path if os.path.isabs(path) else os.path.join(src_dir, path) self.cmake_sources += [CMakeBuildFile(path, i.get('isCMake', False), i.get('isGenerated', False))] - def _strip_data(self, data: Any) -> Any: + def _strip_data(self, data: T.Any) -> T.Any: if isinstance(data, list): for idx, i in enumerate(data): data[idx] = self._strip_data(i) @@ -293,7 +293,7 @@ class CMakeFileAPI: return data - def _resolve_references(self, data: Any) -> Any: + def _resolve_references(self, data: T.Any) -> T.Any: if isinstance(data, list): for idx, i in enumerate(data): data[idx] = self._resolve_references(i) diff --git a/mesonbuild/cmake/interpreter.py b/mesonbuild/cmake/interpreter.py index 5f887ee..9155d6d 100644 --- a/mesonbuild/cmake/interpreter.py +++ b/mesonbuild/cmake/interpreter.py @@ -25,10 +25,10 @@ from ..environment import Environment from ..mesonlib import MachineChoice, version_compare from ..compilers.compilers import lang_suffixes, header_suffixes, obj_suffixes, lib_suffixes, is_header from subprocess import Popen, PIPE -from typing import Any, List, Dict, Optional, Set, Union, TYPE_CHECKING from threading import Thread from enum import Enum from functools import lru_cache +import typing as T import os, re from ..mparser import ( @@ -48,7 +48,7 @@ from ..mparser import ( ) -if TYPE_CHECKING: +if T.TYPE_CHECKING: from ..build import Build from ..backend.backends import Backend @@ -136,8 +136,8 @@ class OutputTargetMap: self.tgt_map = {} self.build_dir = build_dir - def add(self, tgt: Union['ConverterTarget', 'ConverterCustomTarget']) -> None: - def assign_keys(keys: List[str]) -> None: + def add(self, tgt: T.Union['ConverterTarget', 'ConverterCustomTarget']) -> None: + def assign_keys(keys: T.List[str]) -> None: for i in [x for x in keys if x]: self.tgt_map[i] = tgt keys = [self._target_key(tgt.cmake_name)] @@ -150,16 +150,16 @@ class OutputTargetMap: keys += [self._base_generated_file_key(x) for x in tgt.original_outputs] assign_keys(keys) - def _return_first_valid_key(self, keys: List[str]) -> Optional[Union['ConverterTarget', 'ConverterCustomTarget']]: + def _return_first_valid_key(self, keys: T.List[str]) -> T.Optional[T.Union['ConverterTarget', 'ConverterCustomTarget']]: for i in keys: if i and i in self.tgt_map: return self.tgt_map[i] return None - def target(self, name: str) -> Optional[Union['ConverterTarget', 'ConverterCustomTarget']]: + def target(self, name: str) -> T.Optional[T.Union['ConverterTarget', 'ConverterCustomTarget']]: return self._return_first_valid_key([self._target_key(name)]) - def artifact(self, name: str) -> Optional[Union['ConverterTarget', 'ConverterCustomTarget']]: + def artifact(self, name: str) -> T.Optional[T.Union['ConverterTarget', 'ConverterCustomTarget']]: keys = [] candidates = [name, OutputTargetMap.rm_so_version.sub('', name)] for i in lib_suffixes: @@ -172,11 +172,11 @@ class OutputTargetMap: keys += [self._rel_artifact_key(i), os.path.basename(i), self._base_artifact_key(i)] return self._return_first_valid_key(keys) - def generated(self, name: str) -> Optional[Union['ConverterTarget', 'ConverterCustomTarget']]: + def generated(self, name: str) -> T.Optional[T.Union['ConverterTarget', 'ConverterCustomTarget']]: return self._return_first_valid_key([self._rel_generated_file_key(name), self._base_generated_file_key(name)]) # Utility functions to generate local keys - def _rel_path(self, fname: str) -> Optional[str]: + def _rel_path(self, fname: str) -> T.Optional[str]: fname = os.path.normpath(os.path.join(self.build_dir, fname)) if os.path.commonpath([self.build_dir, fname]) != self.build_dir: return None @@ -185,14 +185,14 @@ class OutputTargetMap: def _target_key(self, tgt_name: str) -> str: return '__tgt_{}__'.format(tgt_name) - def _rel_generated_file_key(self, fname: str) -> Optional[str]: + def _rel_generated_file_key(self, fname: str) -> T.Optional[str]: path = self._rel_path(fname) return '__relgen_{}__'.format(path) if path else None def _base_generated_file_key(self, fname: str) -> str: return '__gen_{}__'.format(os.path.basename(fname)) - def _rel_artifact_key(self, fname: str) -> Optional[str]: + def _rel_artifact_key(self, fname: str) -> T.Optional[str]: path = self._rel_path(fname) return '__relart_{}__'.format(path) if path else None @@ -393,7 +393,7 @@ class ConverterTarget: self.generated = [x for x in self.generated if any([x.endswith(y) for y in supported])] # Make paths relative - def rel_path(x: str, is_header: bool, is_generated: bool) -> Optional[str]: + def rel_path(x: str, is_header: bool, is_generated: bool) -> T.Optional[str]: if not os.path.isabs(x): x = os.path.normpath(os.path.join(self.src_dir, x)) if not os.path.exists(x) and not any([x.endswith(y) for y in obj_suffixes]) and not is_generated: @@ -458,7 +458,7 @@ class ConverterTarget: if tgt: self.depends.append(tgt) - def process_object_libs(self, obj_target_list: List['ConverterTarget'], linker_workaround: bool): + def process_object_libs(self, obj_target_list: T.List['ConverterTarget'], linker_workaround: bool): # Try to detect the object library(s) from the generated input sources temp = [x for x in self.generated if isinstance(x, str)] temp = [os.path.basename(x) for x in temp] @@ -475,7 +475,7 @@ class ConverterTarget: # suffix and just produces object files like `foo.obj`. Thus we have to do our best to # undo this step and guess the correct language suffix of the object file. This is done # by trying all language suffixes meson knows and checking if one of them fits. - candidates = [j] # type: List[str] + candidates = [j] # type: T.List[str] if not any([j.endswith('.' + x) for x in exts]): mlog.warning('Object files do not contain source file extensions, thus falling back to guessing them.', once=True) candidates += ['{}.{}'.format(j, x) for x in exts] @@ -506,8 +506,8 @@ class ConverterTarget: self.compile_opts[lang] += [x for x in opts if x not in self.compile_opts[lang]] @lru_cache(maxsize=None) - def _all_source_suffixes(self) -> List[str]: - suffixes = [] # type: List[str] + def _all_source_suffixes(self) -> T.List[str]: + suffixes = [] # type: T.List[str] for exts in lang_suffixes.values(): suffixes += [x for x in exts] return suffixes @@ -599,7 +599,7 @@ class ConverterCustomTarget: def __repr__(self) -> str: return '<{}: {} {}>'.format(self.__class__.__name__, self.name, self.outputs) - def postprocess(self, output_target_map: OutputTargetMap, root_src_dir: str, subdir: str, build_dir: str, all_outputs: List[str]) -> None: + def postprocess(self, output_target_map: OutputTargetMap, root_src_dir: str, subdir: str, build_dir: str, all_outputs: T.List[str]) -> None: # Default the working directory to the CMake build dir. This # is not 100% correct, since it should be the value of # ${CMAKE_CURRENT_BINARY_DIR} when add_custom_command is @@ -626,7 +626,7 @@ class ConverterCustomTarget: # Ensure that there is no duplicate output in the project so # that meson can handle cases where the same filename is # generated in multiple directories - temp_outputs = [] # type: List[str] + temp_outputs = [] # type: T.List[str] for i in self.outputs: if i in all_outputs: old = str(i) @@ -689,7 +689,7 @@ class ConverterCustomTarget: new_deps += [i] self.depends = list(set(new_deps)) - def get_ref(self, fname: str) -> Optional[CustomTargetReference]: + def get_ref(self, fname: str) -> T.Optional[CustomTargetReference]: fname = os.path.basename(fname) try: if fname in self.conflict_map: @@ -724,7 +724,7 @@ class CMakeInterpreter: self.install_prefix = install_prefix self.env = env self.backend_name = backend.name - self.linkers = set() # type: Set[str] + self.linkers = set() # type: T.Set[str] self.cmake_api = CMakeAPI.SERVER self.client = CMakeClient(self.env) self.fileapi = CMakeFileAPI(self.build_dir) @@ -738,7 +738,7 @@ class CMakeInterpreter: self.project_name = '' self.languages = [] self.targets = [] - self.custom_targets = [] # type: List[ConverterCustomTarget] + self.custom_targets = [] # type: T.List[ConverterCustomTarget] self.trace = CMakeTraceParser() self.output_target_map = OutputTargetMap(self.build_dir) @@ -746,7 +746,7 @@ class CMakeInterpreter: self.generated_targets = {} self.internal_name_map = {} - def configure(self, extra_cmake_options: List[str]) -> None: + def configure(self, extra_cmake_options: T.List[str]) -> None: for_machine = MachineChoice.HOST # TODO make parameter # Find CMake cmake_exe = CMakeExecutor(self.env, '>=3.7', for_machine) @@ -835,7 +835,7 @@ class CMakeInterpreter: if proc.returncode != 0: raise CMakeException('Failed to configure the CMake subproject') - def initialise(self, extra_cmake_options: List[str]) -> None: + def initialise(self, extra_cmake_options: T.List[str]) -> None: # Run configure the old way because doing it # with the server doesn't work for some reason # Additionally, the File API requires a configure anyway @@ -893,7 +893,7 @@ class CMakeInterpreter: self.trace.parse(self.raw_trace) # Find all targets - added_target_names = [] # type: List[str] + added_target_names = [] # type: T.List[str] for i in self.codemodel_configs: for j in i.projects: if not self.project_name: @@ -929,7 +929,7 @@ class CMakeInterpreter: # First pass: Basic target cleanup object_libs = [] - custom_target_outputs = [] # type: List[str] + custom_target_outputs = [] # type: T.List[str] for i in self.custom_targets: i.postprocess(self.output_target_map, self.src_dir, self.subdir, self.build_dir, custom_target_outputs) for i in self.targets: @@ -1029,7 +1029,7 @@ class CMakeInterpreter: processed = {} name_map = {} - def extract_tgt(tgt: Union[ConverterTarget, ConverterCustomTarget, CustomTargetReference]) -> IdNode: + def extract_tgt(tgt: T.Union[ConverterTarget, ConverterCustomTarget, CustomTargetReference]) -> IdNode: tgt_name = None if isinstance(tgt, (ConverterTarget, ConverterCustomTarget)): tgt_name = tgt.name @@ -1039,7 +1039,7 @@ class CMakeInterpreter: res_var = processed[tgt_name]['tgt'] return id_node(res_var) if res_var else None - def detect_cycle(tgt: Union[ConverterTarget, ConverterCustomTarget]) -> None: + def detect_cycle(tgt: T.Union[ConverterTarget, ConverterCustomTarget]) -> None: if tgt.name in processing: raise CMakeException('Cycle in CMake inputs/dependencies detected') processing.append(tgt.name) @@ -1056,7 +1056,7 @@ class CMakeInterpreter: # First handle inter target dependencies link_with = [] - objec_libs = [] # type: List[IdNode] + objec_libs = [] # type: T.List[IdNode] sources = [] generated = [] generated_filenames = [] @@ -1186,7 +1186,7 @@ class CMakeInterpreter: detect_cycle(tgt) tgt_var = tgt.name # type: str - def resolve_source(x: Any) -> Any: + def resolve_source(x: T.Any) -> T.Any: if isinstance(x, ConverterTarget): if x.name not in processed: process_target(x) @@ -1236,7 +1236,7 @@ class CMakeInterpreter: self.internal_name_map = name_map return root_cb - def target_info(self, target: str) -> Optional[Dict[str, str]]: + def target_info(self, target: str) -> T.Optional[T.Dict[str, str]]: # Try resolving the target name # start by checking if there is a 100% match (excluding the name prefix) prx_tgt = generated_target_name_prefix + target @@ -1249,7 +1249,7 @@ class CMakeInterpreter: return self.generated_targets[target] return None - def target_list(self) -> List[str]: + def target_list(self) -> T.List[str]: prx_str = generated_target_name_prefix prx_len = len(prx_str) res = [x for x in self.generated_targets.keys()] diff --git a/mesonbuild/cmake/traceparser.py b/mesonbuild/cmake/traceparser.py index 84b2120..ceb5b02 100644 --- a/mesonbuild/cmake/traceparser.py +++ b/mesonbuild/cmake/traceparser.py @@ -19,7 +19,7 @@ from .common import CMakeException from .generator import parse_generator_expressions from .. import mlog -from typing import List, Tuple, Optional +import typing as T import re import os @@ -35,7 +35,7 @@ class CMakeTraceLine: return s.format(self.file, self.line, self.func, self.args) class CMakeTarget: - def __init__(self, name, target_type, properties=None, imported: bool = False, tline: Optional[CMakeTraceLine] = None): + def __init__(self, name, target_type, properties=None, imported: bool = False, tline: T.Optional[CMakeTraceLine] = None): if properties is None: properties = {} self.name = name @@ -55,9 +55,9 @@ class CMakeTarget: class CMakeGeneratorTarget(CMakeTarget): def __init__(self, name): super().__init__(name, 'CUSTOM', {}) - self.outputs = [] # type: List[str] - self.command = [] # type: List[List[str]] - self.working_dir = None # type: Optional[str] + self.outputs = [] # type: T.List[str] + self.command = [] # type: T.List[T.List[str]] + self.working_dir = None # type: T.Optional[str] class CMakeTraceParser: def __init__(self, permissive: bool = False): @@ -67,8 +67,8 @@ class CMakeTraceParser: # Dict of CMakeTarget self.targets = {} - # List of targes that were added with add_custom_command to generate files - self.custom_targets = [] # type: List[CMakeGeneratorTarget] + # T.List of targes that were added with add_custom_command to generate files + self.custom_targets = [] # type: T.List[CMakeGeneratorTarget] self.permissive = permissive # type: bool @@ -101,7 +101,7 @@ class CMakeTraceParser: if(fn): fn(l) - def get_first_cmake_var_of(self, var_list: List[str]) -> List[str]: + def get_first_cmake_var_of(self, var_list: T.List[str]) -> T.List[str]: # Return the first found CMake variable in list var_list for i in var_list: if i in self.vars: @@ -109,7 +109,7 @@ class CMakeTraceParser: return [] - def get_cmake_var(self, var: str) -> List[str]: + def get_cmake_var(self, var: str) -> T.List[str]: # Return the value of the CMake variable var or an empty list if var does not exist if var in self.vars: return self.vars[var] @@ -382,7 +382,7 @@ class CMakeTraceParser: # option 1 first and fall back to 2, as 1 requires less code and less # synchroniztion for cmake changes. - arglist = [] # type: List[Tuple[str, List[str]]] + arglist = [] # type: T.List[T.Tuple[str, T.List[str]]] name = args.pop(0) values = [] prop_regex = re.compile(r'^[A-Z_]+$') @@ -437,7 +437,7 @@ class CMakeTraceParser: # DOC: https://cmake.org/cmake/help/latest/command/target_link_libraries.html self._parse_common_target_options('target_link_options', 'LINK_LIBRARIES', 'INTERFACE_LINK_LIBRARIES', tline) - def _parse_common_target_options(self, func: str, private_prop: str, interface_prop: str, tline: CMakeTraceLine, ignore: Optional[List[str]] = None, paths: bool = False): + def _parse_common_target_options(self, func: str, private_prop: str, interface_prop: str, tline: CMakeTraceLine, ignore: T.Optional[T.List[str]] = None, paths: bool = False): if ignore is None: ignore = ['BEFORE'] @@ -509,14 +509,14 @@ class CMakeTraceParser: yield CMakeTraceLine(file, line, func, args) - def _guess_files(self, broken_list: List[str]) -> List[str]: + def _guess_files(self, broken_list: T.List[str]) -> T.List[str]: #Try joining file paths that contain spaces reg_start = re.compile(r'^([A-Za-z]:)?/.*/[^./]+$') reg_end = re.compile(r'^.*\.[a-zA-Z]+$') - fixed_list = [] # type: List[str] - curr_str = None # type: Optional[str] + fixed_list = [] # type: T.List[str] + curr_str = None # type: T.Optional[str] for i in broken_list: if curr_str is None: diff --git a/mesonbuild/compilers/c.py b/mesonbuild/compilers/c.py index 8a15609..d9d81d6 100644 --- a/mesonbuild/compilers/c.py +++ b/mesonbuild/compilers/c.py @@ -13,7 +13,7 @@ # limitations under the License. import os.path -import typing +import typing as T from .. import coredata from ..mesonlib import MachineChoice, MesonException, mlog, version_compare @@ -35,7 +35,7 @@ from .compilers import ( Compiler, ) -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..envconfig import MachineInfo @@ -51,7 +51,7 @@ class CCompiler(CLikeCompiler, Compiler): language = 'c' def __init__(self, exelist, version, for_machine: MachineChoice, is_cross: bool, - info: 'MachineInfo', exe_wrapper: typing.Optional[str] = None, **kwargs): + info: 'MachineInfo', exe_wrapper: T.Optional[str] = None, **kwargs): # If a child ObjC or CPP class has already set it, don't set it ourselves Compiler.__init__(self, exelist, version, for_machine, info, **kwargs) CLikeCompiler.__init__(self, is_cross, exe_wrapper) diff --git a/mesonbuild/compilers/compilers.py b/mesonbuild/compilers/compilers.py index d54f7da..ec2b24b 100644 --- a/mesonbuild/compilers/compilers.py +++ b/mesonbuild/compilers/compilers.py @@ -14,7 +14,7 @@ import contextlib, os.path, re, tempfile import collections.abc -import typing +import typing as T from ..linkers import StaticLinker, GnuLikeDynamicLinkerMixin, SolarisDynamicLinker from .. import coredata @@ -28,7 +28,7 @@ from ..envconfig import ( Properties, ) -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..coredata import OptionDictType from ..envconfig import MachineInfo from ..environment import Environment @@ -386,7 +386,7 @@ class RunResult: self.stdout = stdout self.stderr = stderr -class CompilerArgs(typing.MutableSequence[str]): +class CompilerArgs(T.MutableSequence[str]): ''' List-like class that manages a list of compiler arguments. Should be used while constructing compiler arguments from various sources. Can be @@ -441,34 +441,34 @@ class CompilerArgs(typing.MutableSequence[str]): # *always* de-dup these because they're special arguments to the linker always_dedup_args = tuple('-l' + lib for lib in unixy_compiler_internal_libs) - def __init__(self, compiler: typing.Union['Compiler', StaticLinker], - iterable: typing.Optional[typing.Iterable[str]] = None): + def __init__(self, compiler: T.Union['Compiler', StaticLinker], + iterable: T.Optional[T.Iterable[str]] = None): self.compiler = compiler - self.__container = list(iterable) if iterable is not None else [] # type: typing.List[str] + self.__container = list(iterable) if iterable is not None else [] # type: T.List[str] - @typing.overload + @T.overload def __getitem__(self, index: int) -> str: pass - @typing.overload - def __getitem__(self, index: slice) -> typing.List[str]: + @T.overload + def __getitem__(self, index: slice) -> T.List[str]: pass def __getitem__(self, index): return self.__container[index] - @typing.overload + @T.overload def __setitem__(self, index: int, value: str) -> None: pass - @typing.overload - def __setitem__(self, index: slice, value: typing.List[str]) -> None: + @T.overload + def __setitem__(self, index: slice, value: T.List[str]) -> None: pass def __setitem__(self, index, value) -> None: self.__container[index] = value - def __delitem__(self, index: typing.Union[int, slice]) -> None: + def __delitem__(self, index: T.Union[int, slice]) -> None: del self.__container[index] def __len__(self) -> int: @@ -531,7 +531,7 @@ class CompilerArgs(typing.MutableSequence[str]): return True return False - def to_native(self, copy: bool = False) -> typing.List[str]: + def to_native(self, copy: bool = False) -> T.List[str]: # Check if we need to add --start/end-group for circular dependencies # between static libraries, and for recursively searching for symbols # needed by static libraries that are provided by object files or @@ -563,7 +563,7 @@ class CompilerArgs(typing.MutableSequence[str]): # Remove system/default include paths added with -isystem if hasattr(self.compiler, 'get_default_include_dirs'): default_dirs = self.compiler.get_default_include_dirs() - bad_idx_list = [] # type: typing.List[int] + bad_idx_list = [] # type: T.List[int] for i, each in enumerate(new): # Remove the -isystem and the path if the path is a default path if (each == '-isystem' and @@ -589,7 +589,7 @@ class CompilerArgs(typing.MutableSequence[str]): else: self.__container.append(arg) - def extend_direct(self, iterable: typing.Iterable[str]) -> None: + def extend_direct(self, iterable: T.Iterable[str]) -> None: ''' Extend using the elements in the specified iterable without any reordering or de-dup except for absolute paths where the order of @@ -598,7 +598,7 @@ class CompilerArgs(typing.MutableSequence[str]): for elem in iterable: self.append_direct(elem) - def extend_preserving_lflags(self, iterable: typing.Iterable[str]) -> None: + def extend_preserving_lflags(self, iterable: T.Iterable[str]) -> None: normal_flags = [] lflags = [] for i in iterable: @@ -609,18 +609,18 @@ class CompilerArgs(typing.MutableSequence[str]): self.extend(normal_flags) self.extend_direct(lflags) - def __add__(self, args: typing.Iterable[str]) -> 'CompilerArgs': + def __add__(self, args: T.Iterable[str]) -> 'CompilerArgs': new = self.copy() new += args return new - def __iadd__(self, args: typing.Iterable[str]) -> 'CompilerArgs': + def __iadd__(self, args: T.Iterable[str]) -> 'CompilerArgs': ''' Add two CompilerArgs while taking into account overriding of arguments and while preserving the order of arguments as much as possible ''' - pre = [] # type: typing.List[str] - post = [] # type: typing.List[str] + pre = [] # type: T.List[str] + post = [] # type: T.List[str] if not isinstance(args, collections.abc.Iterable): raise TypeError('can only concatenate Iterable[str] (not "{}") to CompilerArgs'.format(args)) for arg in args: @@ -650,12 +650,12 @@ class CompilerArgs(typing.MutableSequence[str]): self.__container += post return self - def __radd__(self, args: typing.Iterable[str]): + def __radd__(self, args: T.Iterable[str]): new = CompilerArgs(self.compiler, args) new += self return new - def __eq__(self, other: typing.Any) -> typing.Union[bool, 'NotImplemented']: + def __eq__(self, other: T.Any) -> T.Union[bool, 'NotImplemented']: # Only allow equality checks against other CompilerArgs and lists instances if isinstance(other, CompilerArgs): return self.compiler == other.compiler and self.__container == other.__container @@ -666,7 +666,7 @@ class CompilerArgs(typing.MutableSequence[str]): def append(self, arg: str) -> None: self.__iadd__([arg]) - def extend(self, args: typing.Iterable[str]) -> None: + def extend(self, args: T.Iterable[str]) -> None: self.__iadd__(args) def __repr__(self) -> str: @@ -680,11 +680,11 @@ class Compiler: # manually searched. internal_libs = () - LINKER_PREFIX = None # type: typing.Union[None, str, typing.List[str]] + LINKER_PREFIX = None # type: T.Union[None, str, T.List[str]] INVOKES_LINKER = True def __init__(self, exelist, version, for_machine: MachineChoice, info: 'MachineInfo', - linker: typing.Optional['DynamicLinker'] = None, **kwargs): + linker: T.Optional['DynamicLinker'] = None, **kwargs): if isinstance(exelist, str): self.exelist = [exelist] elif isinstance(exelist, list): @@ -742,7 +742,7 @@ class Compiler: def get_default_suffix(self) -> str: return self.default_suffix - def get_define(self, dname, prefix, env, extra_args, dependencies) -> typing.Tuple[str, bool]: + def get_define(self, dname, prefix, env, extra_args, dependencies) -> T.Tuple[str, bool]: raise EnvironmentException('%s does not support get_define ' % self.get_id()) def compute_int(self, expression, low, high, guess, prefix, env, extra_args, dependencies) -> int: @@ -752,11 +752,11 @@ class Compiler: raise EnvironmentException('%s does not support compute_parameters_with_absolute_paths ' % self.get_id()) def has_members(self, typename, membernames, prefix, env, *, - extra_args=None, dependencies=None) -> typing.Tuple[bool, bool]: + extra_args=None, dependencies=None) -> T.Tuple[bool, bool]: raise EnvironmentException('%s does not support has_member(s) ' % self.get_id()) def has_type(self, typename, prefix, env, extra_args, *, - dependencies=None) -> typing.Tuple[bool, bool]: + dependencies=None) -> T.Tuple[bool, bool]: raise EnvironmentException('%s does not support has_type ' % self.get_id()) def symbols_have_underscore_prefix(self, env) -> bool: @@ -765,10 +765,10 @@ class Compiler: def get_exelist(self): return self.exelist[:] - def get_linker_exelist(self) -> typing.List[str]: + def get_linker_exelist(self) -> T.List[str]: return self.linker.get_exelist() - def get_linker_output_args(self, outputname: str) -> typing.List[str]: + def get_linker_output_args(self, outputname: str) -> T.List[str]: return self.linker.get_output_args(outputname) def get_builtin_define(self, *args, **kwargs): @@ -799,31 +799,31 @@ class Compiler: """ return [] - def get_linker_args_from_envvars(self) -> typing.List[str]: + def get_linker_args_from_envvars(self) -> T.List[str]: return self.linker.get_args_from_envvars() - def get_options(self) -> typing.Dict[str, coredata.UserOption]: + def get_options(self) -> T.Dict[str, coredata.UserOption]: return {} def get_option_compile_args(self, options): return [] - def get_option_link_args(self, options: 'OptionDictType') -> typing.List[str]: + def get_option_link_args(self, options: 'OptionDictType') -> T.List[str]: return self.linker.get_option_args(options) - def check_header(self, *args, **kwargs) -> typing.Tuple[bool, bool]: + def check_header(self, *args, **kwargs) -> T.Tuple[bool, bool]: raise EnvironmentException('Language %s does not support header checks.' % self.get_display_language()) - def has_header(self, *args, **kwargs) -> typing.Tuple[bool, bool]: + def has_header(self, *args, **kwargs) -> T.Tuple[bool, bool]: raise EnvironmentException('Language %s does not support header checks.' % self.get_display_language()) - def has_header_symbol(self, *args, **kwargs) -> typing.Tuple[bool, bool]: + def has_header_symbol(self, *args, **kwargs) -> T.Tuple[bool, bool]: raise EnvironmentException('Language %s does not support header symbol checks.' % self.get_display_language()) - def compiles(self, *args, **kwargs) -> typing.Tuple[bool, bool]: + def compiles(self, *args, **kwargs) -> T.Tuple[bool, bool]: raise EnvironmentException('Language %s does not support compile checks.' % self.get_display_language()) - def links(self, *args, **kwargs) -> typing.Tuple[bool, bool]: + def links(self, *args, **kwargs) -> T.Tuple[bool, bool]: raise EnvironmentException('Language %s does not support link checks.' % self.get_display_language()) def run(self, *args, **kwargs) -> RunResult: @@ -835,7 +835,7 @@ class Compiler: def alignment(self, *args, **kwargs) -> int: raise EnvironmentException('Language %s does not support alignment checks.' % self.get_display_language()) - def has_function(self, *args, **kwargs) -> typing.Tuple[bool, bool]: + def has_function(self, *args, **kwargs) -> T.Tuple[bool, bool]: raise EnvironmentException('Language %s does not support function checks.' % self.get_display_language()) @classmethod @@ -844,7 +844,7 @@ class Compiler: return args[:] @classmethod - def native_args_to_unix(cls, args: typing.List[str]) -> typing.List[str]: + def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]: "Always returns a copy that can be independently mutated" return args[:] @@ -857,12 +857,12 @@ class Compiler: def get_program_dirs(self, *args, **kwargs): return [] - def has_multi_arguments(self, args, env) -> typing.Tuple[bool, bool]: + def has_multi_arguments(self, args, env) -> T.Tuple[bool, bool]: raise EnvironmentException( 'Language {} does not support has_multi_arguments.'.format( self.get_display_language())) - def has_multi_link_arguments(self, args: typing.List[str], env: 'Environment') -> typing.Tuple[bool, bool]: + def has_multi_link_arguments(self, args: T.List[str], env: 'Environment') -> T.Tuple[bool, bool]: return self.linker.has_multi_arguments(args, env) def _get_compile_output(self, dirname, mode): @@ -976,22 +976,22 @@ class Compiler: def get_compile_debugfile_args(self, rel_obj, **kwargs): return [] - def get_link_debugfile_args(self, targetfile: str) -> typing.List[str]: + def get_link_debugfile_args(self, targetfile: str) -> T.List[str]: return self.linker.get_debugfile_args(targetfile) - def get_std_shared_lib_link_args(self) -> typing.List[str]: + def get_std_shared_lib_link_args(self) -> T.List[str]: return self.linker.get_std_shared_lib_args() - def get_std_shared_module_link_args(self, options: 'OptionDictType') -> typing.List[str]: + def get_std_shared_module_link_args(self, options: 'OptionDictType') -> T.List[str]: return self.linker.get_std_shared_module_args(options) - def get_link_whole_for(self, args: typing.List[str]) -> typing.List[str]: + def get_link_whole_for(self, args: T.List[str]) -> T.List[str]: return self.linker.get_link_whole_for(args) - def get_allow_undefined_link_args(self) -> typing.List[str]: + def get_allow_undefined_link_args(self) -> T.List[str]: return self.linker.get_allow_undefined_args() - def no_undefined_link_args(self) -> typing.List[str]: + def no_undefined_link_args(self) -> T.List[str]: return self.linker.no_undefined_args() # Compiler arguments needed to enable the given instruction set. @@ -1002,7 +1002,7 @@ class Compiler: def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str, rpath_paths: str, build_rpath: str, - install_rpath: str) -> typing.List[str]: + install_rpath: str) -> T.List[str]: return self.linker.build_rpath_args( env, build_dir, from_dir, rpath_paths, build_rpath, install_rpath) @@ -1033,7 +1033,7 @@ class Compiler: m = 'Language {} does not support position-independent executable' raise EnvironmentException(m.format(self.get_display_language())) - def get_pie_link_args(self) -> typing.List[str]: + def get_pie_link_args(self) -> T.List[str]: return self.linker.get_pie_args() def get_argument_syntax(self): @@ -1055,40 +1055,40 @@ class Compiler: raise EnvironmentException( '%s does not support get_profile_use_args ' % self.get_id()) - def get_undefined_link_args(self) -> typing.List[str]: + def get_undefined_link_args(self) -> T.List[str]: return self.linker.get_undefined_link_args() def remove_linkerlike_args(self, args): return [x for x in args if not x.startswith('-Wl')] - def get_lto_compile_args(self) -> typing.List[str]: + def get_lto_compile_args(self) -> T.List[str]: return [] - def get_lto_link_args(self) -> typing.List[str]: + def get_lto_link_args(self) -> T.List[str]: return self.linker.get_lto_args() - def sanitizer_compile_args(self, value: str) -> typing.List[str]: + def sanitizer_compile_args(self, value: str) -> T.List[str]: return [] - def sanitizer_link_args(self, value: str) -> typing.List[str]: + def sanitizer_link_args(self, value: str) -> T.List[str]: return self.linker.sanitizer_args(value) - def get_asneeded_args(self) -> typing.List[str]: + def get_asneeded_args(self) -> T.List[str]: return self.linker.get_asneeded_args() - def bitcode_args(self) -> typing.List[str]: + def bitcode_args(self) -> T.List[str]: return self.linker.bitcode_args() - def get_linker_debug_crt_args(self) -> typing.List[str]: + def get_linker_debug_crt_args(self) -> T.List[str]: return self.linker.get_debug_crt_args() - def get_buildtype_linker_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_linker_args(self, buildtype: str) -> T.List[str]: return self.linker.get_buildtype_args(buildtype) def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str, suffix: str, soversion: str, - darwin_versions: typing.Tuple[str, str], - is_shared_module: bool) -> typing.List[str]: + darwin_versions: T.Tuple[str, str], + is_shared_module: bool) -> T.List[str]: return self.linker.get_soname_args( env, prefix, shlib_name, suffix, soversion, darwin_versions, is_shared_module) @@ -1103,7 +1103,7 @@ class Compiler: return dep.get_link_args() @classmethod - def use_linker_args(cls, linker: str) -> typing.List[str]: + def use_linker_args(cls, linker: str) -> T.List[str]: """Get a list of arguments to pass to the compiler to set the linker. """ return [] @@ -1131,12 +1131,12 @@ def get_largefile_args(compiler): return [] -def get_args_from_envvars(lang: str, use_linker_args: bool) -> typing.Tuple[typing.List[str], typing.List[str]]: +def get_args_from_envvars(lang: str, use_linker_args: bool) -> T.Tuple[T.List[str], T.List[str]]: """ Returns a tuple of (compile_flags, link_flags) for the specified language from the inherited environment """ - def log_var(var, val: typing.Optional[str]): + def log_var(var, val: T.Optional[str]): if val: mlog.log('Appending {} from environment: {!r}'.format(var, val)) else: @@ -1145,8 +1145,8 @@ def get_args_from_envvars(lang: str, use_linker_args: bool) -> typing.Tuple[typi if lang not in cflags_mapping: return [], [] - compile_flags = [] # type: typing.List[str] - link_flags = [] # type: typing.List[str] + compile_flags = [] # type: T.List[str] + link_flags = [] # type: T.List[str] env_compile_flags = os.environ.get(cflags_mapping[lang]) log_var(cflags_mapping[lang], env_compile_flags) @@ -1179,8 +1179,8 @@ def get_args_from_envvars(lang: str, use_linker_args: bool) -> typing.Tuple[typi return compile_flags, link_flags -def get_global_options(lang: str, comp: typing.Type[Compiler], - properties: Properties) -> typing.Dict[str, coredata.UserOption]: +def get_global_options(lang: str, comp: T.Type[Compiler], + properties: Properties) -> T.Dict[str, coredata.UserOption]: """Retreive options that apply to all compilers for a given language.""" description = 'Extra arguments passed to the {}'.format(lang) opts = { diff --git a/mesonbuild/compilers/cpp.py b/mesonbuild/compilers/cpp.py index f8ded00..a09c611 100644 --- a/mesonbuild/compilers/cpp.py +++ b/mesonbuild/compilers/cpp.py @@ -15,7 +15,7 @@ import copy import functools import os.path -import typing +import typing as T from .. import coredata from .. import mlog @@ -39,7 +39,7 @@ from .mixins.pgi import PGICompiler from .mixins.islinker import BasicLinkerIsCompilerMixin, LinkerEnvVarsMixin from .mixins.emscripten import EmscriptenMixin -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..envconfig import MachineInfo @@ -62,7 +62,7 @@ class CPPCompiler(CLikeCompiler, Compiler): language = 'cpp' def __init__(self, exelist, version, for_machine: MachineChoice, is_cross: bool, - info: 'MachineInfo', exe_wrap: typing.Optional[str] = None, **kwargs): + info: 'MachineInfo', exe_wrap: T.Optional[str] = None, **kwargs): # If a child ObjCPP class has already set it, don't set it ourselves Compiler.__init__(self, exelist, version, for_machine, info, **kwargs) CLikeCompiler.__init__(self, is_cross, exe_wrap) @@ -431,7 +431,7 @@ class VisualStudioLikeCPPCompilerMixin: def get_option_link_args(self, options): return options['cpp_winlibs'].value[:] - def _get_options_impl(self, opts, cpp_stds: typing.List[str]): + def _get_options_impl(self, opts, cpp_stds: T.List[str]): opts.update({'cpp_eh': coredata.UserComboOption('C++ exception handling type.', ['none', 'default', 'a', 's', 'sc'], 'default'), diff --git a/mesonbuild/compilers/cs.py b/mesonbuild/compilers/cs.py index d064e7c..843348e 100644 --- a/mesonbuild/compilers/cs.py +++ b/mesonbuild/compilers/cs.py @@ -13,14 +13,14 @@ # limitations under the License. import os.path, subprocess -import typing +import typing as T from ..mesonlib import EnvironmentException from .compilers import Compiler, MachineChoice, mono_buildtype_args from .mixins.islinker import BasicLinkerIsCompilerMixin -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..envconfig import MachineInfo cs_optimization_args = {'0': [], diff --git a/mesonbuild/compilers/cuda.py b/mesonbuild/compilers/cuda.py index 385e4cf..e839f53 100644 --- a/mesonbuild/compilers/cuda.py +++ b/mesonbuild/compilers/cuda.py @@ -13,7 +13,7 @@ # limitations under the License. import os.path -import typing +import typing as T from functools import partial from .. import coredata @@ -22,7 +22,7 @@ from ..mesonlib import EnvironmentException, MachineChoice, Popen_safe, OptionOv from .compilers import (Compiler, cuda_buildtype_args, cuda_optimization_args, cuda_debug_args) -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..environment import Environment # noqa: F401 from ..envconfig import MachineInfo @@ -197,9 +197,9 @@ class CudaCompiler(Compiler): return args + self._to_host_flags(self.host_compiler.get_option_compile_args(self._to_host_compiler_options(options))) @classmethod - def _cook_link_args(cls, args: typing.List[str]) -> typing.List[str]: + def _cook_link_args(cls, args: T.List[str]) -> T.List[str]: # Prepare link args for nvcc - cooked = [] # type: typing.List[str] + cooked = [] # type: T.List[str] for arg in args: if arg.startswith('-Wl,'): # strip GNU-style -Wl prefix arg = arg.replace('-Wl,', '', 1) @@ -263,7 +263,7 @@ class CudaCompiler(Compiler): def get_depfile_suffix(self): return 'd' - def get_linker_debug_crt_args(self) -> typing.List[str]: + def get_linker_debug_crt_args(self) -> T.List[str]: return self._cook_link_args(self.host_compiler.get_linker_debug_crt_args()) def get_buildtype_linker_args(self, buildtype): @@ -271,7 +271,7 @@ class CudaCompiler(Compiler): def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str, rpath_paths: str, build_rpath: str, - install_rpath: str) -> typing.List[str]: + install_rpath: str) -> T.List[str]: return self._cook_link_args(self.host_compiler.build_rpath_args( env, build_dir, from_dir, rpath_paths, build_rpath, install_rpath)) @@ -284,10 +284,10 @@ class CudaCompiler(Compiler): def compute_parameters_with_absolute_paths(self, parameter_list, build_dir): return [] - def get_output_args(self, target: str) -> typing.List[str]: + def get_output_args(self, target: str) -> T.List[str]: return ['-o', target] - def get_std_exe_link_args(self) -> typing.List[str]: + def get_std_exe_link_args(self) -> T.List[str]: return self._cook_link_args(self.host_compiler.get_std_exe_link_args()) def find_library(self, libname, env, extra_dirs, libtype: LibType = LibType.PREFER_SHARED): diff --git a/mesonbuild/compilers/d.py b/mesonbuild/compilers/d.py index 15770a5..b974504 100644 --- a/mesonbuild/compilers/d.py +++ b/mesonbuild/compilers/d.py @@ -13,7 +13,7 @@ # limitations under the License. import os.path, subprocess -import typing +import typing as T from ..mesonlib import ( EnvironmentException, MachineChoice, version_compare, @@ -30,7 +30,7 @@ from .compilers import ( from .mixins.gnu import GnuCompiler from .mixins.islinker import LinkerEnvVarsMixin, BasicLinkerIsCompilerMixin -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..envconfig import MachineInfo d_feature_args = {'gcc': {'unittest': '-funittest', @@ -388,7 +388,7 @@ class DmdLikeCompilerMixin: assert(buildtype == 'custom') raise EnvironmentException('Requested C runtime based on buildtype, but buildtype is "custom".') - def get_soname_args(self, *args, **kwargs) -> typing.List[str]: + def get_soname_args(self, *args, **kwargs) -> T.List[str]: # LDC and DMD actually do use a linker, but they proxy all of that with # their own arguments soargs = [] @@ -396,7 +396,7 @@ class DmdLikeCompilerMixin: soargs.append('-L=' + arg) return soargs - def get_allow_undefined_link_args(self) -> typing.List[str]: + def get_allow_undefined_link_args(self) -> T.List[str]: args = [] for arg in self.linker.get_allow_undefined_args(): args.append('-L=' + arg) @@ -654,7 +654,7 @@ class GnuDCompiler(DCompiler, GnuCompiler): return parameter_list - def get_allow_undefined_link_args(self) -> typing.List[str]: + def get_allow_undefined_link_args(self) -> T.List[str]: return self.linker.get_allow_undefined_args() diff --git a/mesonbuild/compilers/fortran.py b/mesonbuild/compilers/fortran.py index 4aff72e..73a8e24 100644 --- a/mesonbuild/compilers/fortran.py +++ b/mesonbuild/compilers/fortran.py @@ -13,7 +13,7 @@ # limitations under the License. from pathlib import Path -from typing import TYPE_CHECKING, List +import typing as T import subprocess, os from .. import coredata @@ -35,7 +35,7 @@ from mesonbuild.mesonlib import ( version_compare, EnvironmentException, MesonException, MachineChoice, LibType ) -if TYPE_CHECKING: +if T.TYPE_CHECKING: from ..envconfig import MachineInfo @@ -189,7 +189,7 @@ class GnuFortranCompiler(GnuCompiler, FortranCompiler): 'none')}) return opts - def get_option_compile_args(self, options) -> List[str]: + def get_option_compile_args(self, options) -> T.List[str]: args = [] std = options['fortran_std'] if std.value != 'none': @@ -295,7 +295,7 @@ class IntelFortranCompiler(IntelGnuLikeCompiler, FortranCompiler): 'none')}) return opts - def get_option_compile_args(self, options) -> List[str]: + def get_option_compile_args(self, options) -> T.List[str]: args = [] std = options['fortran_std'] stds = {'legacy': 'none', 'f95': 'f95', 'f2003': 'f03', 'f2008': 'f08', 'f2018': 'f18'} @@ -315,7 +315,7 @@ class IntelFortranCompiler(IntelGnuLikeCompiler, FortranCompiler): def language_stdlib_only_link_flags(self): return ['-lifcore', '-limf'] - def get_dependency_gen_args(self, outtarget: str, outfile: str) -> List[str]: + def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]: return ['-gen-dep=' + outtarget, '-gen-depformat=make'] @@ -345,7 +345,7 @@ class IntelClFortranCompiler(IntelVisualStudioLikeCompiler, FortranCompiler): 'none')}) return opts - def get_option_compile_args(self, options) -> List[str]: + def get_option_compile_args(self, options) -> T.List[str]: args = [] std = options['fortran_std'] stds = {'legacy': 'none', 'f95': 'f95', 'f2003': 'f03', 'f2008': 'f08', 'f2018': 'f18'} @@ -353,7 +353,7 @@ class IntelClFortranCompiler(IntelVisualStudioLikeCompiler, FortranCompiler): args.append('/stand:' + stds[std.value]) return args - def get_module_outdir_args(self, path) -> List[str]: + def get_module_outdir_args(self, path) -> T.List[str]: return ['/module:' + path] @@ -388,7 +388,7 @@ class PGIFortranCompiler(PGICompiler, FortranCompiler): '2': default_warn_args, '3': default_warn_args + ['-Mdclchk']} - def language_stdlib_only_link_flags(self) -> List[str]: + def language_stdlib_only_link_flags(self) -> T.List[str]: return ['-lpgf90rtl', '-lpgf90', '-lpgf90_rpm1', '-lpgf902', '-lpgf90rtl', '-lpgftnrtl', '-lrt'] @@ -406,7 +406,7 @@ class FlangFortranCompiler(ClangCompiler, FortranCompiler): '2': default_warn_args, '3': default_warn_args} - def language_stdlib_only_link_flags(self) -> List[str]: + def language_stdlib_only_link_flags(self) -> T.List[str]: return ['-lflang', '-lpgmath'] class Open64FortranCompiler(FortranCompiler): diff --git a/mesonbuild/compilers/java.py b/mesonbuild/compilers/java.py index bb62fb2..5aeb250 100644 --- a/mesonbuild/compilers/java.py +++ b/mesonbuild/compilers/java.py @@ -15,13 +15,13 @@ import os.path import shutil import subprocess -import typing +import typing as T from ..mesonlib import EnvironmentException, MachineChoice from .compilers import Compiler, java_buildtype_args from .mixins.islinker import BasicLinkerIsCompilerMixin -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..envconfig import MachineInfo class JavaCompiler(BasicLinkerIsCompilerMixin, Compiler): diff --git a/mesonbuild/compilers/mixins/arm.py b/mesonbuild/compilers/mixins/arm.py index 28708d5..d15faec 100644 --- a/mesonbuild/compilers/mixins/arm.py +++ b/mesonbuild/compilers/mixins/arm.py @@ -16,13 +16,13 @@ import os import re -import typing +import typing as T from ... import mesonlib from ..compilers import clike_debug_args from .clang import clang_color_args -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ...environment import Environment arm_buildtype_args = { @@ -32,7 +32,7 @@ arm_buildtype_args = { 'release': ['-O3', '-Otime'], 'minsize': ['-O3', '-Ospace'], 'custom': [], -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] arm_optimization_args = { '0': ['-O0'], @@ -41,7 +41,7 @@ arm_optimization_args = { '2': ['-O2'], '3': ['-O3'], 's': [], -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] armclang_buildtype_args = { 'plain': [], @@ -50,7 +50,7 @@ armclang_buildtype_args = { 'release': ['-Os'], 'minsize': ['-Oz'], 'custom': [], -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] armclang_optimization_args = { '0': ['-O0'], @@ -59,7 +59,7 @@ armclang_optimization_args = { '2': ['-O2'], '3': ['-O3'], 's': ['-Os'] -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] class ArmCompiler: @@ -68,7 +68,7 @@ class ArmCompiler: if not self.is_cross: raise mesonlib.EnvironmentException('armcc supports only cross-compilation.') self.id = 'arm' - default_warn_args = [] # type: typing.List[str] + default_warn_args = [] # type: T.List[str] self.warn_args = {'0': [], '1': default_warn_args, '2': default_warn_args + [], @@ -76,22 +76,22 @@ class ArmCompiler: # Assembly self.can_compile_suffixes.add('s') - def get_pic_args(self) -> typing.List[str]: + def get_pic_args(self) -> T.List[str]: # FIXME: Add /ropi, /rwpi, /fpic etc. qualifiers to --apcs return [] - def get_buildtype_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_args(self, buildtype: str) -> T.List[str]: return arm_buildtype_args[buildtype] # Override CCompiler.get_always_args - def get_always_args(self) -> typing.List[str]: + def get_always_args(self) -> T.List[str]: return [] # Override CCompiler.get_dependency_gen_args - def get_dependency_gen_args(self, outtarget: str, outfile: str) -> typing.List[str]: + def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]: return [] - def get_pch_use_args(self, pch_dir: str, header: str) -> typing.List[str]: + def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]: # FIXME: Add required arguments # NOTE from armcc user guide: # "Support for Precompiled Header (PCH) files is deprecated from ARM Compiler 5.05 @@ -106,19 +106,19 @@ class ArmCompiler: # PCH files." return 'pch' - def thread_flags(self, env: 'Environment') -> typing.List[str]: + def thread_flags(self, env: 'Environment') -> T.List[str]: return [] - def get_coverage_args(self) -> typing.List[str]: + def get_coverage_args(self) -> T.List[str]: return [] - def get_optimization_args(self, optimization_level: str) -> typing.List[str]: + def get_optimization_args(self, optimization_level: str) -> T.List[str]: return arm_optimization_args[optimization_level] - def get_debug_args(self, is_debug: bool) -> typing.List[str]: + def get_debug_args(self, is_debug: bool) -> T.List[str]: return clike_debug_args[is_debug] - def compute_parameters_with_absolute_paths(self, parameter_list: typing.List[str], build_dir: str) -> typing.List[str]: + def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]: for idx, i in enumerate(parameter_list): if i[:2] == '-I' or i[:2] == '-L': parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:])) @@ -159,37 +159,37 @@ class ArmclangCompiler: # Assembly self.can_compile_suffixes.update('s') - def get_pic_args(self) -> typing.List[str]: + def get_pic_args(self) -> T.List[str]: # PIC support is not enabled by default for ARM, # if users want to use it, they need to add the required arguments explicitly return [] - def get_colorout_args(self, colortype: str) -> typing.List[str]: + def get_colorout_args(self, colortype: str) -> T.List[str]: return clang_color_args[colortype][:] - def get_buildtype_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_args(self, buildtype: str) -> T.List[str]: return armclang_buildtype_args[buildtype] def get_pch_suffix(self) -> str: return 'gch' - def get_pch_use_args(self, pch_dir: str, header: str) -> typing.List[str]: + def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]: # Workaround for Clang bug http://llvm.org/bugs/show_bug.cgi?id=15136 # This flag is internal to Clang (or at least not documented on the man page) # so it might change semantics at any time. return ['-include-pch', os.path.join(pch_dir, self.get_pch_name(header))] # Override CCompiler.get_dependency_gen_args - def get_dependency_gen_args(self, outtarget: str, outfile: str) -> typing.List[str]: + def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]: return [] - def get_optimization_args(self, optimization_level: str) -> typing.List[str]: + def get_optimization_args(self, optimization_level: str) -> T.List[str]: return armclang_optimization_args[optimization_level] - def get_debug_args(self, is_debug: bool) -> typing.List[str]: + def get_debug_args(self, is_debug: bool) -> T.List[str]: return clike_debug_args[is_debug] - def compute_parameters_with_absolute_paths(self, parameter_list: typing.List[str], build_dir: str) -> typing.List[str]: + def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]: for idx, i in enumerate(parameter_list): if i[:2] == '-I' or i[:2] == '-L': parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:])) diff --git a/mesonbuild/compilers/mixins/ccrx.py b/mesonbuild/compilers/mixins/ccrx.py index c6979a4..5e61805 100644 --- a/mesonbuild/compilers/mixins/ccrx.py +++ b/mesonbuild/compilers/mixins/ccrx.py @@ -15,11 +15,11 @@ """Representations specific to the Renesas CC-RX compiler family.""" import os -import typing +import typing as T from ...mesonlib import EnvironmentException -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ...environment import Environment ccrx_buildtype_args = { @@ -29,7 +29,7 @@ ccrx_buildtype_args = { 'release': [], 'minsize': [], 'custom': [], -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] ccrx_optimization_args = { '0': ['-optimize=0'], @@ -38,12 +38,12 @@ ccrx_optimization_args = { '2': ['-optimize=2'], '3': ['-optimize=max'], 's': ['-optimize=2', '-size'] -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] ccrx_debug_args = { False: [], True: ['-debug'] -} # type: typing.Dict[bool, typing.List[str]] +} # type: T.Dict[bool, T.List[str]] class CcrxCompiler: @@ -53,44 +53,44 @@ class CcrxCompiler: self.id = 'ccrx' # Assembly self.can_compile_suffixes.update('s') - default_warn_args = [] # type: typing.List[str] + default_warn_args = [] # type: T.List[str] self.warn_args = {'0': [], '1': default_warn_args, '2': default_warn_args + [], '3': default_warn_args + []} - def get_pic_args(self) -> typing.List[str]: + def get_pic_args(self) -> T.List[str]: # PIC support is not enabled by default for CCRX, # if users want to use it, they need to add the required arguments explicitly return [] - def get_buildtype_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_args(self, buildtype: str) -> T.List[str]: return ccrx_buildtype_args[buildtype] def get_pch_suffix(self) -> str: return 'pch' - def get_pch_use_args(self, pch_dir: str, header: str) -> typing.List[str]: + def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]: return [] # Override CCompiler.get_dependency_gen_args - def get_dependency_gen_args(self, outtarget: str, outfile: str) -> typing.List[str]: + def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]: return [] - def thread_flags(self, env: 'Environment') -> typing.List[str]: + def thread_flags(self, env: 'Environment') -> T.List[str]: return [] - def get_coverage_args(self) -> typing.List[str]: + def get_coverage_args(self) -> T.List[str]: return [] - def get_optimization_args(self, optimization_level: str) -> typing.List[str]: + def get_optimization_args(self, optimization_level: str) -> T.List[str]: return ccrx_optimization_args[optimization_level] - def get_debug_args(self, is_debug: bool) -> typing.List[str]: + def get_debug_args(self, is_debug: bool) -> T.List[str]: return ccrx_debug_args[is_debug] @classmethod - def unix_args_to_native(cls, args: typing.List[str]) -> typing.List[str]: + def unix_args_to_native(cls, args: T.List[str]) -> T.List[str]: result = [] for i in args: if i.startswith('-D'): @@ -108,7 +108,7 @@ class CcrxCompiler: result.append(i) return result - def compute_parameters_with_absolute_paths(self, parameter_list: typing.List[str], build_dir: str) -> typing.List[str]: + def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]: for idx, i in enumerate(parameter_list): if i[:9] == '-include=': parameter_list[idx] = i[:9] + os.path.normpath(os.path.join(build_dir, i[9:])) diff --git a/mesonbuild/compilers/mixins/clang.py b/mesonbuild/compilers/mixins/clang.py index 16f4659..1c52af2 100644 --- a/mesonbuild/compilers/mixins/clang.py +++ b/mesonbuild/compilers/mixins/clang.py @@ -15,14 +15,14 @@ """Abstractions for the LLVM/Clang compiler family.""" import os -import typing +import typing as T from ... import mesonlib from ...linkers import AppleDynamicLinker from ..compilers import clike_optimization_args from .gnu import GnuLikeCompiler -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ...environment import Environment from ...dependencies import Dependency # noqa: F401 @@ -30,7 +30,7 @@ clang_color_args = { 'auto': ['-Xclang', '-fcolor-diagnostics'], 'always': ['-Xclang', '-fcolor-diagnostics'], 'never': ['-Xclang', '-fno-color-diagnostics'], -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] class ClangCompiler(GnuLikeCompiler): @@ -45,22 +45,22 @@ class ClangCompiler(GnuLikeCompiler): # All Clang backends can also do LLVM IR self.can_compile_suffixes.add('ll') - def get_colorout_args(self, colortype: str) -> typing.List[str]: + def get_colorout_args(self, colortype: str) -> T.List[str]: return clang_color_args[colortype][:] - def get_optimization_args(self, optimization_level: str) -> typing.List[str]: + def get_optimization_args(self, optimization_level: str) -> T.List[str]: return clike_optimization_args[optimization_level] def get_pch_suffix(self) -> str: return 'pch' - def get_pch_use_args(self, pch_dir: str, header: str) -> typing.List[str]: + def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]: # Workaround for Clang bug http://llvm.org/bugs/show_bug.cgi?id=15136 # This flag is internal to Clang (or at least not documented on the man page) # so it might change semantics at any time. return ['-include-pch', os.path.join(pch_dir, self.get_pch_name(header))] - def has_multi_arguments(self, args: typing.List[str], env: 'Environment') -> typing.List[str]: + def has_multi_arguments(self, args: T.List[str], env: 'Environment') -> T.List[str]: myargs = ['-Werror=unknown-warning-option', '-Werror=unused-command-line-argument'] if mesonlib.version_compare(self.version, '>=3.6.0'): myargs.append('-Werror=ignored-optimization-argument') @@ -69,8 +69,8 @@ class ClangCompiler(GnuLikeCompiler): env) def has_function(self, funcname: str, prefix: str, env: 'Environment', *, - extra_args: typing.Optional[typing.List[str]] = None, - dependencies: typing.Optional[typing.List['Dependency']] = None) -> bool: + extra_args: T.Optional[T.List[str]] = None, + dependencies: T.Optional[T.List['Dependency']] = None) -> bool: if extra_args is None: extra_args = [] # Starting with XCode 8, we need to pass this to force linker @@ -83,7 +83,7 @@ class ClangCompiler(GnuLikeCompiler): return super().has_function(funcname, prefix, env, extra_args=extra_args, dependencies=dependencies) - def openmp_flags(self) -> typing.List[str]: + def openmp_flags(self) -> T.List[str]: if mesonlib.version_compare(self.version, '>=3.8.0'): return ['-fopenmp'] elif mesonlib.version_compare(self.version, '>=3.7.0'): diff --git a/mesonbuild/compilers/mixins/clike.py b/mesonbuild/compilers/mixins/clike.py index b5516b0..3aca5fe 100644 --- a/mesonbuild/compilers/mixins/clike.py +++ b/mesonbuild/compilers/mixins/clike.py @@ -26,7 +26,7 @@ import itertools import os import re import subprocess -import typing +import typing as T from pathlib import Path from ... import mesonlib @@ -35,7 +35,7 @@ from ... import mlog from .. import compilers from .visualstudio import VisualStudioLikeCompiler -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ...environment import Environment @@ -50,7 +50,7 @@ class CLikeCompiler: find_framework_cache = {} internal_libs = compilers.unixy_compiler_internal_libs - def __init__(self, is_cross: bool, exe_wrapper: typing.Optional[str] = None): + def __init__(self, is_cross: bool, exe_wrapper: T.Optional[str] = None): # If a child ObjC or CPP class has already set it, don't set it ourselves self.is_cross = is_cross self.can_compile_suffixes.add('h') @@ -117,7 +117,7 @@ class CLikeCompiler: def get_coverage_args(self): return ['--coverage'] - def get_coverage_link_args(self) -> typing.List[str]: + def get_coverage_link_args(self) -> T.List[str]: return self.linker.get_coverage_args() def get_werror_args(self): @@ -134,7 +134,7 @@ class CLikeCompiler: return ['-isystem', path] return ['-I' + path] - def get_compiler_dirs(self, env: 'Environment', name: str) -> typing.List[str]: + def get_compiler_dirs(self, env: 'Environment', name: str) -> T.List[str]: ''' Get dirs from the compiler, either `libraries:` or `programs:` ''' @@ -177,28 +177,28 @@ class CLikeCompiler: ''' return self.get_compiler_dirs(env, 'programs') - def get_pic_args(self) -> typing.List[str]: + def get_pic_args(self) -> T.List[str]: return ['-fPIC'] def name_string(self) -> str: return ' '.join(self.exelist) - def get_pch_use_args(self, pch_dir: str, header: str) -> typing.List[str]: + def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]: return ['-include', os.path.basename(header)] def get_pch_name(self, header_name: str) -> str: return os.path.basename(header_name) + '.' + self.get_pch_suffix() - def get_linker_search_args(self, dirname: str) -> typing.List[str]: + def get_linker_search_args(self, dirname: str) -> T.List[str]: return self.linker.get_search_args(dirname) def get_default_include_dirs(self): return [] - def gen_export_dynamic_link_args(self, env: 'Environment') -> typing.List[str]: + def gen_export_dynamic_link_args(self, env: 'Environment') -> T.List[str]: return self.linker.export_dynamic_args(env) - def gen_import_library_args(self, implibname: str) -> typing.List[str]: + def gen_import_library_args(self, implibname: str) -> T.List[str]: return self.linker.import_library_args(implibname) def sanity_check_impl(self, work_dir, environment, sname, code): @@ -901,7 +901,7 @@ class CLikeCompiler: return [f] @staticmethod - def _get_file_from_list(env, files: typing.List[str]) -> Path: + def _get_file_from_list(env, files: T.List[str]) -> Path: ''' We just check whether the library exists. We can't do a link check because the library might have unresolved symbols that require other @@ -1055,10 +1055,10 @@ class CLikeCompiler: raise mesonlib.MesonException('Cannot find frameworks with non-clang compiler') return self.find_framework_impl(name, env, extra_dirs, allow_system) - def get_crt_compile_args(self, crt_val: str, buildtype: str) -> typing.List[str]: + def get_crt_compile_args(self, crt_val: str, buildtype: str) -> T.List[str]: return [] - def get_crt_link_args(self, crt_val: str, buildtype: str) -> typing.List[str]: + def get_crt_link_args(self, crt_val: str, buildtype: str) -> T.List[str]: return [] def thread_flags(self, env): @@ -1067,7 +1067,7 @@ class CLikeCompiler: return [] return ['-pthread'] - def thread_link_flags(self, env: 'Environment') -> typing.List[str]: + def thread_link_flags(self, env: 'Environment') -> T.List[str]: return self.linker.thread_flags(env) def linker_to_compiler_args(self, args): diff --git a/mesonbuild/compilers/mixins/elbrus.py b/mesonbuild/compilers/mixins/elbrus.py index e157d87..87bf52a 100644 --- a/mesonbuild/compilers/mixins/elbrus.py +++ b/mesonbuild/compilers/mixins/elbrus.py @@ -15,21 +15,21 @@ """Abstractions for the Elbrus family of compilers.""" import os -import typing +import typing as T import subprocess import re from .gnu import GnuLikeCompiler from ...mesonlib import Popen_safe -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ...environment import Environment class ElbrusCompiler(GnuLikeCompiler): # Elbrus compiler is nearly like GCC, but does not support # PCH, LTO, sanitizers and color output as of version 1.21.x. - def __init__(self, defines: typing.Dict[str, str]): + def __init__(self, defines: T.Dict[str, str]): super().__init__() self.id = 'lcc' self.base_options = ['b_pgo', 'b_coverage', @@ -38,7 +38,7 @@ class ElbrusCompiler(GnuLikeCompiler): # FIXME: use _build_wrapper to call this so that linker flags from the env # get applied - def get_library_dirs(self, env: 'Environment', elf_class: typing.Optional[int] = None) -> typing.List[str]: + def get_library_dirs(self, env: 'Environment', elf_class: T.Optional[int] = None) -> T.List[str]: os_env = os.environ.copy() os_env['LC_ALL'] = 'C' stdo = Popen_safe(self.exelist + ['--print-search-dirs'], env=os_env)[1] @@ -49,7 +49,7 @@ class ElbrusCompiler(GnuLikeCompiler): return [os.path.realpath(p) for p in libstr.split(':') if os.path.exists(p)] return [] - def get_program_dirs(self, env: 'Environment') -> typing.List[str]: + def get_program_dirs(self, env: 'Environment') -> T.List[str]: os_env = os.environ.copy() os_env['LC_ALL'] = 'C' stdo = Popen_safe(self.exelist + ['--print-search-dirs'], env=os_env)[1] @@ -60,7 +60,7 @@ class ElbrusCompiler(GnuLikeCompiler): return [os.path.realpath(p) for p in libstr.split(':')] return [] - def get_default_include_dirs(self) -> typing.List[str]: + def get_default_include_dirs(self) -> T.List[str]: os_env = os.environ.copy() os_env['LC_ALL'] = 'C' p = subprocess.Popen(self.exelist + ['-xc', '-E', '-v', '-'], env=os_env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/mesonbuild/compilers/mixins/emscripten.py b/mesonbuild/compilers/mixins/emscripten.py index 98513e5..945a67d 100644 --- a/mesonbuild/compilers/mixins/emscripten.py +++ b/mesonbuild/compilers/mixins/emscripten.py @@ -15,7 +15,7 @@ """Provides a mixin for shared code between C and C++ Emscripten compilers.""" import os.path -import typing +import typing as T from ...mesonlib import MesonException @@ -26,10 +26,10 @@ class EmscriptenMixin: def get_soname_args(self, *args, **kwargs): raise MesonException('Emscripten does not support shared libraries.') - def get_allow_undefined_link_args(self) -> typing.List[str]: + def get_allow_undefined_link_args(self) -> T.List[str]: return ['-s', 'ERROR_ON_UNDEFINED_SYMBOLS=0'] - def get_linker_output_args(self, output: str) -> typing.List[str]: + def get_linker_output_args(self, output: str) -> T.List[str]: return ['-o', output] def _get_compile_output(self, dirname, mode): diff --git a/mesonbuild/compilers/mixins/gnu.py b/mesonbuild/compilers/mixins/gnu.py index dcca227..ae4b7db 100644 --- a/mesonbuild/compilers/mixins/gnu.py +++ b/mesonbuild/compilers/mixins/gnu.py @@ -20,12 +20,12 @@ import os import pathlib import re import subprocess -import typing +import typing as T from ... import mesonlib from ... import mlog -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ...coredata import UserOption # noqa: F401 from ...environment import Environment @@ -34,7 +34,7 @@ if typing.TYPE_CHECKING: clike_debug_args = { False: [], True: ['-g'], -} # type: typing.Dict[bool, typing.List[str]] +} # type: T.Dict[bool, T.List[str]] gnulike_buildtype_args = { 'plain': [], @@ -43,7 +43,7 @@ gnulike_buildtype_args = { 'release': [], 'minsize': [], 'custom': [], -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] gnu_optimization_args = { '0': [], @@ -52,7 +52,7 @@ gnu_optimization_args = { '2': ['-O2'], '3': ['-O3'], 's': ['-Os'], -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] gnulike_instruction_set_args = { 'mmx': ['-mmmx'], @@ -65,7 +65,7 @@ gnulike_instruction_set_args = { 'avx': ['-mavx'], 'avx2': ['-mavx2'], 'neon': ['-mfpu=neon'], -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] gnu_symbol_visibility_args = { '': [], @@ -74,17 +74,17 @@ gnu_symbol_visibility_args = { 'hidden': ['-fvisibility=hidden'], 'protected': ['-fvisibility=protected'], 'inlineshidden': ['-fvisibility=hidden', '-fvisibility-inlines-hidden'], -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] gnu_color_args = { 'auto': ['-fdiagnostics-color=auto'], 'always': ['-fdiagnostics-color=always'], 'never': ['-fdiagnostics-color=never'], -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] @functools.lru_cache(maxsize=None) -def gnulike_default_include_dirs(compiler: typing.Tuple[str], lang: str) -> typing.List[str]: +def gnulike_default_include_dirs(compiler: T.Tuple[str], lang: str) -> T.List[str]: lang_map = { 'c': 'c', 'cpp': 'c++', @@ -149,45 +149,45 @@ class GnuLikeCompiler(metaclass=abc.ABCMeta): # All GCC-like backends can do assembly self.can_compile_suffixes.add('s') - def get_pic_args(self) -> typing.List[str]: + def get_pic_args(self) -> T.List[str]: if self.info.is_windows() or self.info.is_cygwin() or self.info.is_darwin(): return [] # On Window and OS X, pic is always on. return ['-fPIC'] - def get_pie_args(self) -> typing.List[str]: + def get_pie_args(self) -> T.List[str]: return ['-fPIE'] - def get_buildtype_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_args(self, buildtype: str) -> T.List[str]: return gnulike_buildtype_args[buildtype] @abc.abstractmethod - def get_optimization_args(self, optimization_level: str) -> typing.List[str]: + def get_optimization_args(self, optimization_level: str) -> T.List[str]: raise NotImplementedError("get_optimization_args not implemented") - def get_debug_args(self, is_debug: bool) -> typing.List[str]: + def get_debug_args(self, is_debug: bool) -> T.List[str]: return clike_debug_args[is_debug] @abc.abstractmethod def get_pch_suffix(self) -> str: raise NotImplementedError("get_pch_suffix not implemented") - def split_shlib_to_parts(self, fname: str) -> typing.Tuple[str, str]: + def split_shlib_to_parts(self, fname: str) -> T.Tuple[str, str]: return os.path.dirname(fname), fname - def get_instruction_set_args(self, instruction_set: str) -> typing.Optional[typing.List[str]]: + def get_instruction_set_args(self, instruction_set: str) -> T.Optional[T.List[str]]: return gnulike_instruction_set_args.get(instruction_set, None) - def get_default_include_dirs(self) -> typing.List[str]: + def get_default_include_dirs(self) -> T.List[str]: return gnulike_default_include_dirs(tuple(self.exelist), self.language) @abc.abstractmethod - def openmp_flags(self) -> typing.List[str]: + def openmp_flags(self) -> T.List[str]: raise NotImplementedError("openmp_flags not implemented") - def gnu_symbol_visibility_args(self, vistype: str) -> typing.List[str]: + def gnu_symbol_visibility_args(self, vistype: str) -> T.List[str]: return gnu_symbol_visibility_args[vistype] - def gen_vs_module_defs_args(self, defsfile: str) -> typing.List[str]: + def gen_vs_module_defs_args(self, defsfile: str) -> T.List[str]: if not isinstance(defsfile, str): raise RuntimeError('Module definitions file should be str') # On Windows targets, .def files may be specified on the linker command @@ -200,18 +200,18 @@ class GnuLikeCompiler(metaclass=abc.ABCMeta): def get_argument_syntax(self) -> str: return 'gcc' - def get_profile_generate_args(self) -> typing.List[str]: + def get_profile_generate_args(self) -> T.List[str]: return ['-fprofile-generate'] - def get_profile_use_args(self) -> typing.List[str]: + def get_profile_use_args(self) -> T.List[str]: return ['-fprofile-use', '-fprofile-correction'] - def get_gui_app_args(self, value: bool) -> typing.List[str]: + def get_gui_app_args(self, value: bool) -> T.List[str]: if self.info.is_windows() or self.info.is_cygwin(): return ['-mwindows' if value else '-mconsole'] return [] - def compute_parameters_with_absolute_paths(self, parameter_list: typing.List[str], build_dir: str) -> typing.List[str]: + def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]: for idx, i in enumerate(parameter_list): if i[:2] == '-I' or i[:2] == '-L': parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:])) @@ -228,7 +228,7 @@ class GnuLikeCompiler(metaclass=abc.ABCMeta): stdo = p.stdo return stdo - def _split_fetch_real_dirs(self, pathstr: str) -> typing.List[str]: + def _split_fetch_real_dirs(self, pathstr: str) -> T.List[str]: # We need to use the path separator used by the compiler for printing # lists of paths ("gcc --print-search-dirs"). By default # we assume it uses the platform native separator. @@ -265,7 +265,7 @@ class GnuLikeCompiler(metaclass=abc.ABCMeta): pass return result - def get_compiler_dirs(self, env: 'Environment', name: str) -> typing.List[str]: + def get_compiler_dirs(self, env: 'Environment', name: str) -> T.List[str]: ''' Get dirs from the compiler, either `libraries:` or `programs:` ''' @@ -275,10 +275,10 @@ class GnuLikeCompiler(metaclass=abc.ABCMeta): return self._split_fetch_real_dirs(line.split('=', 1)[1]) return [] - def get_lto_compile_args(self) -> typing.List[str]: + def get_lto_compile_args(self) -> T.List[str]: return ['-flto'] - def sanitizer_compile_args(self, value: str) -> typing.List[str]: + def sanitizer_compile_args(self, value: str) -> T.List[str]: if value == 'none': return [] args = ['-fsanitize=' + value] @@ -286,16 +286,16 @@ class GnuLikeCompiler(metaclass=abc.ABCMeta): args.append('-fno-omit-frame-pointer') return args - def get_output_args(self, target: str) -> typing.List[str]: + def get_output_args(self, target: str) -> T.List[str]: return ['-o', target] def get_dependency_gen_args(self, outtarget, outfile): return ['-MD', '-MQ', outtarget, '-MF', outfile] - def get_compile_only_args(self) -> typing.List[str]: + def get_compile_only_args(self) -> T.List[str]: return ['-c'] - def get_include_args(self, path: str, is_system: bool) -> typing.List[str]: + def get_include_args(self, path: str, is_system: bool) -> T.List[str]: if not path: path = '.' if is_system: @@ -303,7 +303,7 @@ class GnuLikeCompiler(metaclass=abc.ABCMeta): return ['-I' + path] @classmethod - def use_linker_args(cls, linker: str) -> typing.List[str]: + def use_linker_args(cls, linker: str) -> T.List[str]: return ['-fuse-ld={}'.format(linker)] @@ -313,18 +313,18 @@ class GnuCompiler(GnuLikeCompiler): Compilers imitating GCC (Clang/Intel) should use the GnuLikeCompiler ABC. """ - def __init__(self, defines: typing.Dict[str, str]): + def __init__(self, defines: T.Dict[str, str]): super().__init__() self.id = 'gcc' self.defines = defines or {} self.base_options.append('b_colorout') - def get_colorout_args(self, colortype: str) -> typing.List[str]: + def get_colorout_args(self, colortype: str) -> T.List[str]: if mesonlib.version_compare(self.version, '>=4.9.0'): return gnu_color_args[colortype][:] return [] - def get_warn_args(self, level: str) -> typing.List[str]: + def get_warn_args(self, level: str) -> T.List[str]: args = super().get_warn_args(level) if mesonlib.version_compare(self.version, '<4.8.0') and '-Wpedantic' in args: # -Wpedantic was added in 4.8.0 @@ -335,18 +335,18 @@ class GnuCompiler(GnuLikeCompiler): def has_builtin_define(self, define: str) -> bool: return define in self.defines - def get_builtin_define(self, define: str) -> typing.Optional[str]: + def get_builtin_define(self, define: str) -> T.Optional[str]: if define in self.defines: return self.defines[define] return None - def get_optimization_args(self, optimization_level: str) -> typing.List[str]: + def get_optimization_args(self, optimization_level: str) -> T.List[str]: return gnu_optimization_args[optimization_level] def get_pch_suffix(self) -> str: return 'gch' - def openmp_flags(self) -> typing.List[str]: + def openmp_flags(self) -> T.List[str]: return ['-fopenmp'] def has_arguments(self, args, env, code, mode): diff --git a/mesonbuild/compilers/mixins/intel.py b/mesonbuild/compilers/mixins/intel.py index 91edecd..fbbfdc5 100644 --- a/mesonbuild/compilers/mixins/intel.py +++ b/mesonbuild/compilers/mixins/intel.py @@ -21,13 +21,13 @@ is IntelVisualStudioLikeCompiler. """ import os -import typing +import typing as T from ... import mesonlib from .gnu import GnuLikeCompiler from .visualstudio import VisualStudioLikeCompiler -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: import subprocess # noqa: F401 # XXX: avoid circular dependencies @@ -58,7 +58,7 @@ class IntelGnuLikeCompiler(GnuLikeCompiler): 'release': [], 'minsize': [], 'custom': [], - } # type: typing.Dict[str, typing.List[str]] + } # type: T.Dict[str, T.List[str]] OPTIM_ARGS = { '0': ['-O0'], @@ -84,20 +84,20 @@ class IntelGnuLikeCompiler(GnuLikeCompiler): def get_pch_suffix(self) -> str: return 'pchi' - def get_pch_use_args(self, pch_dir: str, header: str) -> typing.List[str]: + def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]: return ['-pch', '-pch_dir', os.path.join(pch_dir), '-x', self.lang_header, '-include', header, '-x', 'none'] def get_pch_name(self, header_name: str) -> str: return os.path.basename(header_name) + '.' + self.get_pch_suffix() - def openmp_flags(self) -> typing.List[str]: + def openmp_flags(self) -> T.List[str]: if mesonlib.version_compare(self.version, '>=15.0.0'): return ['-qopenmp'] else: return ['-openmp'] - def compiles(self, *args, **kwargs) -> typing.Tuple[bool, bool]: + def compiles(self, *args, **kwargs) -> T.Tuple[bool, bool]: # This covers a case that .get('foo', []) doesn't, that extra_args is # defined and is None extra_args = kwargs.get('extra_args') or [] @@ -113,16 +113,16 @@ class IntelGnuLikeCompiler(GnuLikeCompiler): ] return super().compiles(*args, **kwargs) - def get_profile_generate_args(self) -> typing.List[str]: + def get_profile_generate_args(self) -> T.List[str]: return ['-prof-gen=threadsafe'] - def get_profile_use_args(self) -> typing.List[str]: + def get_profile_use_args(self) -> T.List[str]: return ['-prof-use'] - def get_buildtype_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_args(self, buildtype: str) -> T.List[str]: return self.BUILD_ARGS[buildtype] - def get_optimization_args(self, optimization_level: str) -> typing.List[str]: + def get_optimization_args(self, optimization_level: str) -> T.List[str]: return self.OPTIM_ARGS[optimization_level] @@ -137,7 +137,7 @@ class IntelVisualStudioLikeCompiler(VisualStudioLikeCompiler): 'release': [], 'minsize': [], 'custom': [], - } # type: typing.Dict[str, typing.List[str]] + } # type: T.Dict[str, T.List[str]] OPTIM_ARGS = { '0': ['/O0'], @@ -152,7 +152,7 @@ class IntelVisualStudioLikeCompiler(VisualStudioLikeCompiler): super().__init__(target) self.id = 'intel-cl' - def compile(self, code, *, extra_args: typing.Optional[typing.List[str]] = None, **kwargs) -> typing.Iterator['subprocess.Popen']: + def compile(self, code, *, extra_args: T.Optional[T.List[str]] = None, **kwargs) -> T.Iterator['subprocess.Popen']: # This covers a case that .get('foo', []) doesn't, that extra_args is if kwargs.get('mode', 'compile') != 'link': extra_args = extra_args.copy() if extra_args is not None else [] @@ -166,7 +166,7 @@ class IntelVisualStudioLikeCompiler(VisualStudioLikeCompiler): ]) return super().compile(code, extra_args, **kwargs) - def get_toolset_version(self) -> typing.Optional[str]: + def get_toolset_version(self) -> T.Optional[str]: # Avoid circular dependencies.... from ...environment import search_version @@ -178,11 +178,11 @@ class IntelVisualStudioLikeCompiler(VisualStudioLikeCompiler): version = int(v1 + v2) return self._calculate_toolset_version(version) - def openmp_flags(self) -> typing.List[str]: + def openmp_flags(self) -> T.List[str]: return ['/Qopenmp'] - def get_buildtype_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_args(self, buildtype: str) -> T.List[str]: return self.BUILD_ARGS[buildtype] - def get_optimization_args(self, optimization_level: str) -> typing.List[str]: + def get_optimization_args(self, optimization_level: str) -> T.List[str]: return self.OPTIM_ARGS[optimization_level] diff --git a/mesonbuild/compilers/mixins/islinker.py b/mesonbuild/compilers/mixins/islinker.py index d38f718..4e0af88 100644 --- a/mesonbuild/compilers/mixins/islinker.py +++ b/mesonbuild/compilers/mixins/islinker.py @@ -21,11 +21,11 @@ classes for those cases. """ import os -import typing +import typing as T from ... import mesonlib -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ...coredata import OptionDictType from ...environment import Environment @@ -34,7 +34,7 @@ class LinkerEnvVarsMixin: """Mixin reading LDFLAGS from the environment.""" - def get_linker_args_from_envvars(self) -> typing.List[str]: + def get_linker_args_from_envvars(self) -> T.List[str]: flags = os.environ.get('LDFLAGS') if not flags: return [] @@ -50,83 +50,83 @@ class BasicLinkerIsCompilerMixin: functionality itself. """ - def sanitizer_link_args(self, value: str) -> typing.List[str]: + def sanitizer_link_args(self, value: str) -> T.List[str]: return [] - def get_lto_link_args(self) -> typing.List[str]: + def get_lto_link_args(self) -> T.List[str]: return [] def can_linker_accept_rsp(self) -> bool: return mesonlib.is_windows() - def get_linker_exelist(self) -> typing.List[str]: + def get_linker_exelist(self) -> T.List[str]: return self.exelist.copy() - def get_linker_output_args(self, output: str) -> typing.List[str]: + def get_linker_output_args(self, output: str) -> T.List[str]: return [] - def get_linker_always_args(self) -> typing.List[str]: + def get_linker_always_args(self) -> T.List[str]: return [] def get_linker_lib_prefix(self) -> str: return '' - def get_option_link_args(self, options: 'OptionDictType') -> typing.List[str]: + def get_option_link_args(self, options: 'OptionDictType') -> T.List[str]: return [] - def has_multi_link_args(self, args: typing.List[str], env: 'Environment') -> typing.Tuple[bool, bool]: + def has_multi_link_args(self, args: T.List[str], env: 'Environment') -> T.Tuple[bool, bool]: return False, False - def get_link_debugfile_args(self, targetfile: str) -> typing.List[str]: + def get_link_debugfile_args(self, targetfile: str) -> T.List[str]: return [] - def get_std_shared_lib_link_args(self) -> typing.List[str]: + def get_std_shared_lib_link_args(self) -> T.List[str]: return [] - def get_std_shared_module_args(self, options: 'OptionDictType') -> typing.List[str]: + def get_std_shared_module_args(self, options: 'OptionDictType') -> T.List[str]: return self.get_std_shared_lib_link_args() - def get_link_whole_for(self, args: typing.List[str]) -> typing.List[str]: + def get_link_whole_for(self, args: T.List[str]) -> T.List[str]: raise mesonlib.EnvironmentException( 'Linker {} does not support link_whole'.format(self.id)) - def get_allow_undefined_link_args(self) -> typing.List[str]: + def get_allow_undefined_link_args(self) -> T.List[str]: raise mesonlib.EnvironmentException( 'Linker {} does not support allow undefined'.format(self.id)) - def get_pie_link_args(self) -> typing.List[str]: + def get_pie_link_args(self) -> T.List[str]: m = 'Linker {} does not support position-independent executable' raise mesonlib.EnvironmentException(m.format(self.id)) - def get_undefined_link_args(self) -> typing.List[str]: + def get_undefined_link_args(self) -> T.List[str]: return [] - def get_coverage_link_args(self) -> typing.List[str]: + def get_coverage_link_args(self) -> T.List[str]: m = "Linker {} doesn't implement coverage data generation.".format(self.id) raise mesonlib.EnvironmentException(m) - def no_undefined_link_args(self) -> typing.List[str]: + def no_undefined_link_args(self) -> T.List[str]: return [] - def bitcode_args(self) -> typing.List[str]: + def bitcode_args(self) -> T.List[str]: raise mesonlib.MesonException("This linker doesn't support bitcode bundles") def get_soname_args(self, for_machine: 'mesonlib.MachineChoice', prefix: str, shlib_name: str, suffix: str, soversion: str, - darwin_versions: typing.Tuple[str, str], - is_shared_module: bool) -> typing.List[str]: + darwin_versions: T.Tuple[str, str], + is_shared_module: bool) -> T.List[str]: raise mesonlib.MesonException("This linker doesn't support soname args") def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str, rpath_paths: str, build_rpath: str, - install_rpath: str) -> typing.List[str]: + install_rpath: str) -> T.List[str]: return [] - def get_linker_debug_crt_args(self) -> typing.List[str]: + def get_linker_debug_crt_args(self) -> T.List[str]: return [] - def get_asneeded_args(self) -> typing.List[str]: + def get_asneeded_args(self) -> T.List[str]: return [] - def get_buildtype_linker_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_linker_args(self, buildtype: str) -> T.List[str]: return [] diff --git a/mesonbuild/compilers/mixins/pgi.py b/mesonbuild/compilers/mixins/pgi.py index 065c716..77a7a28 100644 --- a/mesonbuild/compilers/mixins/pgi.py +++ b/mesonbuild/compilers/mixins/pgi.py @@ -14,7 +14,7 @@ """Abstractions for the PGI family of compilers.""" -import typing +import typing as T import os from pathlib import Path @@ -27,7 +27,7 @@ pgi_buildtype_args = { 'release': [], 'minsize': [], 'custom': [], -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] class PGICompiler: @@ -41,50 +41,50 @@ class PGICompiler: '2': default_warn_args, '3': default_warn_args} - def get_module_incdir_args(self) -> typing.Tuple[str]: + def get_module_incdir_args(self) -> T.Tuple[str]: return ('-module', ) - def get_no_warn_args(self) -> typing.List[str]: + def get_no_warn_args(self) -> T.List[str]: return ['-silent'] - def gen_import_library_args(self, implibname: str) -> typing.List[str]: + def gen_import_library_args(self, implibname: str) -> T.List[str]: return [] - def get_pic_args(self) -> typing.List[str]: + def get_pic_args(self) -> T.List[str]: # PGI -fPIC is Linux only. if self.info.is_linux(): return ['-fPIC'] return [] - def openmp_flags(self) -> typing.List[str]: + def openmp_flags(self) -> T.List[str]: return ['-mp'] - def get_buildtype_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_args(self, buildtype: str) -> T.List[str]: return pgi_buildtype_args[buildtype] - def get_optimization_args(self, optimization_level: str) -> typing.List[str]: + def get_optimization_args(self, optimization_level: str) -> T.List[str]: return clike_optimization_args[optimization_level] - def get_debug_args(self, is_debug: bool) -> typing.List[str]: + def get_debug_args(self, is_debug: bool) -> T.List[str]: return clike_debug_args[is_debug] - def compute_parameters_with_absolute_paths(self, parameter_list: typing.List[str], build_dir: str) -> typing.List[str]: + def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]: for idx, i in enumerate(parameter_list): if i[:2] == '-I' or i[:2] == '-L': parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:])) return parameter_list - def get_dependency_gen_args(self, outtarget: str, outfile: str) -> typing.List[str]: + def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]: return [] - def get_always_args(self) -> typing.List[str]: + def get_always_args(self) -> T.List[str]: return [] def get_pch_suffix(self) -> str: # PGI defaults to .pch suffix for PCH on Linux and Windows with --pch option return 'pch' - def get_pch_use_args(self, pch_dir: str, header: str) -> typing.List[str]: + def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]: # PGI supports PCH for C++ only. hdr = Path(pch_dir).resolve().parent / header if self.language == 'cpp': diff --git a/mesonbuild/compilers/mixins/visualstudio.py b/mesonbuild/compilers/mixins/visualstudio.py index 8e18144..735dae6 100644 --- a/mesonbuild/compilers/mixins/visualstudio.py +++ b/mesonbuild/compilers/mixins/visualstudio.py @@ -18,12 +18,12 @@ interface. import abc import os -import typing +import typing as T from ... import mesonlib from ... import mlog -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ...environment import Environment vs32_instruction_set_args = { @@ -36,7 +36,7 @@ vs32_instruction_set_args = { 'avx': ['/arch:AVX'], 'avx2': ['/arch:AVX2'], 'neon': None, -} # typing.Dicst[str, typing.Optional[typing.List[str]]] +} # T.Dicst[str, T.Optional[T.List[str]]] # The 64 bit compiler defaults to /arch:avx. vs64_instruction_set_args = { @@ -50,7 +50,7 @@ vs64_instruction_set_args = { 'avx': ['/arch:AVX'], 'avx2': ['/arch:AVX2'], 'neon': None, -} # typing.Dicst[str, typing.Optional[typing.List[str]]] +} # T.Dicst[str, T.Optional[T.List[str]]] msvc_buildtype_args = { 'plain': [], @@ -59,7 +59,7 @@ msvc_buildtype_args = { 'release': ["/Ob2", "/Gw"], 'minsize': ["/Zi", "/Gw"], 'custom': [], -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] msvc_optimization_args = { '0': [], @@ -68,12 +68,12 @@ msvc_optimization_args = { '2': ['/O2'], '3': ['/O2'], 's': ['/O1'], # Implies /Os. -} # type: typing.Dict[str, typing.List[str]] +} # type: T.Dict[str, T.List[str]] msvc_debug_args = { False: [], True: [] # Fixme! -} # type: typing.Dict[bool, typing.List[str]] +} # type: T.Dict[bool, T.List[str]] class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): @@ -99,7 +99,7 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): 'mdd': ['/MDd'], 'mt': ['/MT'], 'mtd': ['/MTd'], - } # type: typing.Dict[str, typing.List[str]] + } # type: T.Dict[str, T.List[str]] # /showIncludes is needed for build dependency tracking in Ninja # See: https://ninja-build.org/manual.html#_deps @@ -109,7 +109,7 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): '1': ['/W2'], '2': ['/W3'], '3': ['/W4'], - } # type: typing.Dict[str, typing.List[str]] + } # type: T.Dict[str, T.List[str]] INVOKES_LINKER = False @@ -127,10 +127,10 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): self.linker.machine = self.machine # Override CCompiler.get_always_args - def get_always_args(self) -> typing.List[str]: + def get_always_args(self) -> T.List[str]: return self.always_args - def get_buildtype_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_args(self, buildtype: str) -> T.List[str]: args = msvc_buildtype_args[buildtype] if self.id == 'msvc' and mesonlib.version_compare(self.version, '<18.0'): args = [arg for arg in args if arg != '/Gw'] @@ -145,40 +145,40 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): pchname = '.'.join(chopped) return pchname - def get_pch_use_args(self, pch_dir: str, header: str) -> typing.List[str]: + def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]: base = os.path.basename(header) if self.id == 'clang-cl': base = header pchname = self.get_pch_name(header) return ['/FI' + base, '/Yu' + base, '/Fp' + os.path.join(pch_dir, pchname)] - def get_preprocess_only_args(self) -> typing.List[str]: + def get_preprocess_only_args(self) -> T.List[str]: return ['/EP'] - def get_compile_only_args(self) -> typing.List[str]: + def get_compile_only_args(self) -> T.List[str]: return ['/c'] - def get_no_optimization_args(self) -> typing.List[str]: + def get_no_optimization_args(self) -> T.List[str]: return ['/Od'] - def get_output_args(self, target: str) -> typing.List[str]: + def get_output_args(self, target: str) -> T.List[str]: if target.endswith('.exe'): return ['/Fe' + target] return ['/Fo' + target] - def get_optimization_args(self, optimization_level: str) -> typing.List[str]: + def get_optimization_args(self, optimization_level: str) -> T.List[str]: return msvc_optimization_args[optimization_level] - def get_debug_args(self, is_debug: bool) -> typing.List[str]: + def get_debug_args(self, is_debug: bool) -> T.List[str]: return msvc_debug_args[is_debug] - def get_dependency_gen_args(self, outtarget: str, outfile: str) -> typing.List[str]: + def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]: return [] - def linker_to_compiler_args(self, args: typing.List[str]) -> typing.List[str]: + def linker_to_compiler_args(self, args: T.List[str]) -> T.List[str]: return ['/link'] + args - def get_gui_app_args(self, value: bool) -> typing.List[str]: + def get_gui_app_args(self, value: bool) -> T.List[str]: # the default is for the linker to guess the subsystem based on presence # of main or WinMain symbols, so always be explicit if value: @@ -186,33 +186,33 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): else: return ['/SUBSYSTEM:CONSOLE'] - def get_pic_args(self) -> typing.List[str]: + def get_pic_args(self) -> T.List[str]: return [] # PIC is handled by the loader on Windows - def gen_vs_module_defs_args(self, defsfile: str) -> typing.List[str]: + def gen_vs_module_defs_args(self, defsfile: str) -> T.List[str]: if not isinstance(defsfile, str): raise RuntimeError('Module definitions file should be str') # With MSVC, DLLs only export symbols that are explicitly exported, # so if a module defs file is specified, we use that to export symbols return ['/DEF:' + defsfile] - def gen_pch_args(self, header: str, source: str, pchname: str) -> typing.Tuple[str, typing.List[str]]: + def gen_pch_args(self, header: str, source: str, pchname: str) -> T.Tuple[str, T.List[str]]: objname = os.path.splitext(pchname)[0] + '.obj' return objname, ['/Yc' + header, '/Fp' + pchname, '/Fo' + objname] - def gen_import_library_args(self, implibname: str) -> typing.List[str]: + def gen_import_library_args(self, implibname: str) -> T.List[str]: "The name of the outputted import library" return ['/IMPLIB:' + implibname] - def openmp_flags(self) -> typing.List[str]: + def openmp_flags(self) -> T.List[str]: return ['/openmp'] # FIXME, no idea what these should be. - def thread_flags(self, env: 'Environment') -> typing.List[str]: + def thread_flags(self, env: 'Environment') -> T.List[str]: return [] @classmethod - def unix_args_to_native(cls, args: typing.List[str]) -> typing.List[str]: + def unix_args_to_native(cls, args: T.List[str]) -> T.List[str]: result = [] for i in args: # -mms-bitfields is specific to MinGW-GCC @@ -251,7 +251,7 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): return result @classmethod - def native_args_to_unix(cls, args: typing.List[str]) -> typing.List[str]: + def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]: result = [] for arg in args: if arg.startswith(('/LIBPATH:', '-LIBPATH:')): @@ -262,16 +262,16 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): result.append(arg) return result - def get_werror_args(self) -> typing.List[str]: + def get_werror_args(self) -> T.List[str]: return ['/WX'] - def get_include_args(self, path: str, is_system: bool) -> typing.List[str]: + def get_include_args(self, path: str, is_system: bool) -> T.List[str]: if path == '': path = '.' # msvc does not have a concept of system header dirs. return ['-I' + path] - def compute_parameters_with_absolute_paths(self, parameter_list: typing.List[str], build_dir: str) -> typing.List[str]: + def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]: for idx, i in enumerate(parameter_list): if i[:2] == '-I' or i[:2] == '/I': parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:])) @@ -283,7 +283,7 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): # Visual Studio is special. It ignores some arguments it does not # understand and you can't tell it to error out on those. # http://stackoverflow.com/questions/15259720/how-can-i-make-the-microsoft-c-compiler-treat-unknown-flags-as-errors-rather-t - def has_arguments(self, args: typing.List[str], env: 'Environment', code, mode: str) -> typing.Tuple[bool, bool]: + def has_arguments(self, args: T.List[str], env: 'Environment', code, mode: str) -> T.Tuple[bool, bool]: warning_text = '4044' if mode == 'link' else '9002' if self.id == 'clang-cl' and mode != 'link': args = args + ['-Werror=unknown-argument'] @@ -292,7 +292,7 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): return False, p.cached return not(warning_text in p.stde or warning_text in p.stdo), p.cached - def get_compile_debugfile_args(self, rel_obj: str, pch: bool = False) -> typing.List[str]: + def get_compile_debugfile_args(self, rel_obj: str, pch: bool = False) -> T.List[str]: pdbarr = rel_obj.split('.')[:-1] pdbarr += ['pdb'] args = ['/Fd' + '.'.join(pdbarr)] @@ -306,7 +306,7 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): args = ['/FS'] + args return args - def get_instruction_set_args(self, instruction_set: str) -> typing.Optional[typing.List[str]]: + def get_instruction_set_args(self, instruction_set: str) -> T.Optional[T.List[str]]: if self.is_64: return vs64_instruction_set_args.get(instruction_set, None) if self.id == 'msvc' and self.version.split('.')[0] == '16' and instruction_set == 'avx': @@ -316,7 +316,7 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): return None return vs32_instruction_set_args.get(instruction_set, None) - def _calculate_toolset_version(self, version: int) -> typing.Optional[str]: + def _calculate_toolset_version(self, version: int) -> T.Optional[str]: if version < 1310: return '7.0' elif version < 1400: @@ -340,7 +340,7 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): mlog.warning('Could not find toolset for version {!r}'.format(self.version)) return None - def get_toolset_version(self) -> typing.Optional[str]: + def get_toolset_version(self) -> T.Optional[str]: if self.id == 'clang-cl': # I have no idea return '14.1' @@ -352,12 +352,12 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): return None return self._calculate_toolset_version(version) - def get_default_include_dirs(self) -> typing.List[str]: + def get_default_include_dirs(self) -> T.List[str]: if 'INCLUDE' not in os.environ: return [] return os.environ['INCLUDE'].split(os.pathsep) - def get_crt_compile_args(self, crt_val: str, buildtype: str) -> typing.List[str]: + def get_crt_compile_args(self, crt_val: str, buildtype: str) -> T.List[str]: if crt_val in self.crt_args: return self.crt_args[crt_val] assert(crt_val == 'from_buildtype') @@ -376,7 +376,7 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): assert(buildtype == 'custom') raise mesonlib.EnvironmentException('Requested C runtime based on buildtype, but buildtype is "custom".') - def has_func_attribute(self, name: str, env: 'Environment') -> typing.Tuple[bool, bool]: + def has_func_attribute(self, name: str, env: 'Environment') -> T.Tuple[bool, bool]: # MSVC doesn't have __attribute__ like Clang and GCC do, so just return # false without compiling anything return name in ['dllimport', 'dllexport'], False @@ -385,5 +385,5 @@ class VisualStudioLikeCompiler(metaclass=abc.ABCMeta): return 'msvc' @classmethod - def use_linker_args(cls, linker: str) -> typing.List[str]: + def use_linker_args(cls, linker: str) -> T.List[str]: return [] diff --git a/mesonbuild/compilers/objc.py b/mesonbuild/compilers/objc.py index a4aa5dc..cc3fba9 100644 --- a/mesonbuild/compilers/objc.py +++ b/mesonbuild/compilers/objc.py @@ -13,7 +13,7 @@ # limitations under the License. import os.path, subprocess -import typing +import typing as T from ..mesonlib import EnvironmentException, MachineChoice @@ -22,7 +22,7 @@ from .mixins.clike import CLikeCompiler from .mixins.gnu import GnuCompiler from .mixins.clang import ClangCompiler -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..envconfig import MachineInfo @@ -32,7 +32,7 @@ class ObjCCompiler(CLikeCompiler, Compiler): def __init__(self, exelist, version, for_machine: MachineChoice, is_cross: bool, info: 'MachineInfo', - exe_wrap: typing.Optional[str], **kwargs): + exe_wrap: T.Optional[str], **kwargs): Compiler.__init__(self, exelist, version, for_machine, info, **kwargs) CLikeCompiler.__init__(self, is_cross, exe_wrap) diff --git a/mesonbuild/compilers/objcpp.py b/mesonbuild/compilers/objcpp.py index b42cef6..9d58b45 100644 --- a/mesonbuild/compilers/objcpp.py +++ b/mesonbuild/compilers/objcpp.py @@ -13,7 +13,7 @@ # limitations under the License. import os.path, subprocess -import typing +import typing as T from ..mesonlib import EnvironmentException, MachineChoice @@ -22,7 +22,7 @@ from .compilers import Compiler from .mixins.gnu import GnuCompiler from .mixins.clang import ClangCompiler -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..envconfig import MachineInfo class ObjCPPCompiler(CLikeCompiler, Compiler): @@ -31,7 +31,7 @@ class ObjCPPCompiler(CLikeCompiler, Compiler): def __init__(self, exelist, version, for_machine: MachineChoice, is_cross: bool, info: 'MachineInfo', - exe_wrap: typing.Optional[str], **kwargs): + exe_wrap: T.Optional[str], **kwargs): Compiler.__init__(self, exelist, version, for_machine, info, **kwargs) CLikeCompiler.__init__(self, is_cross, exe_wrap) diff --git a/mesonbuild/compilers/rust.py b/mesonbuild/compilers/rust.py index 613414d..c2e21c4 100644 --- a/mesonbuild/compilers/rust.py +++ b/mesonbuild/compilers/rust.py @@ -13,12 +13,12 @@ # limitations under the License. import subprocess, os.path -import typing +import typing as T from ..mesonlib import EnvironmentException, MachineChoice, Popen_safe from .compilers import Compiler, rust_buildtype_args, clike_debug_args -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..envconfig import MachineInfo from ..environment import Environment # noqa: F401 diff --git a/mesonbuild/compilers/swift.py b/mesonbuild/compilers/swift.py index 0909d20..2d2c4e1 100644 --- a/mesonbuild/compilers/swift.py +++ b/mesonbuild/compilers/swift.py @@ -13,13 +13,13 @@ # limitations under the License. import subprocess, os.path -import typing +import typing as T from ..mesonlib import EnvironmentException, MachineChoice from .compilers import Compiler, swift_buildtype_args, clike_debug_args -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..envconfig import MachineInfo swift_optimization_args = {'0': [], diff --git a/mesonbuild/compilers/vala.py b/mesonbuild/compilers/vala.py index 3f4e5fa..012f16a 100644 --- a/mesonbuild/compilers/vala.py +++ b/mesonbuild/compilers/vala.py @@ -13,14 +13,14 @@ # limitations under the License. import os.path -import typing +import typing as T from .. import mlog from ..mesonlib import EnvironmentException, MachineChoice, version_compare from .compilers import Compiler -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..envconfig import MachineInfo class ValaCompiler(Compiler): diff --git a/mesonbuild/coredata.py b/mesonbuild/coredata.py index 3c5306b..e80c524 100644 --- a/mesonbuild/coredata.py +++ b/mesonbuild/coredata.py @@ -26,19 +26,16 @@ from .wrap import WrapMode import ast import argparse import configparser -from typing import ( - Any, Dict, Generic, Iterable, Iterator, List, MutableMapping, Optional, Tuple, Type, TypeVar, Union, - TYPE_CHECKING, -) import enum import shlex +import typing as T -if TYPE_CHECKING: +if T.TYPE_CHECKING: from . import dependencies from .compilers import Compiler # noqa: F401 from .environment import Environment - OptionDictType = Dict[str, 'UserOption[Any]'] + OptionDictType = T.Dict[str, 'UserOption[T.Any]'] version = '0.53.999' backendlist = ['ninja', 'vs', 'vs2010', 'vs2015', 'vs2017', 'vs2019', 'xcode'] @@ -46,9 +43,9 @@ backendlist = ['ninja', 'vs', 'vs2010', 'vs2015', 'vs2017', 'vs2019', 'xcode'] default_yielding = False # Can't bind this near the class method it seems, sadly. -_T = TypeVar('_T') +_T = T.TypeVar('_T') -class UserOption(Generic[_T]): +class UserOption(T.Generic[_T]): def __init__(self, description, choices, yielding): super().__init__() self.choices = choices @@ -65,7 +62,7 @@ class UserOption(Generic[_T]): # Check that the input is a valid value and return the # "cleaned" or "native" version. For example the Boolean # option could take the string "true" and return True. - def validate_value(self, value: Any) -> _T: + def validate_value(self, value: T.Any) -> _T: raise RuntimeError('Derived option class did not override validate_value.') def set_value(self, newvalue): @@ -128,7 +125,7 @@ class UserIntegerOption(UserOption[int]): except ValueError: raise MesonException('Value string "%s" is not convertible to an integer.' % valuestring) -class UserUmaskOption(UserIntegerOption, UserOption[Union[str, int]]): +class UserUmaskOption(UserIntegerOption, UserOption[T.Union[str, int]]): def __init__(self, description, value, yielding=None): super().__init__(description, 0, 0o777, value, yielding) self.choices = ['preserve', '0000-0777'] @@ -150,7 +147,7 @@ class UserUmaskOption(UserIntegerOption, UserOption[Union[str, int]]): raise MesonException('Invalid mode: {}'.format(e)) class UserComboOption(UserOption[str]): - def __init__(self, description, choices: List[str], value, yielding=None): + def __init__(self, description, choices: T.List[str], value, yielding=None): super().__init__(description, choices, yielding) if not isinstance(self.choices, list): raise MesonException('Combo choices must be an array.') @@ -165,14 +162,14 @@ class UserComboOption(UserOption[str]): raise MesonException('Value "%s" for combo option is not one of the choices. Possible choices are: %s.' % (value, optionsstring)) return value -class UserArrayOption(UserOption[List[str]]): +class UserArrayOption(UserOption[T.List[str]]): def __init__(self, description, value, split_args=False, user_input=False, allow_dups=False, **kwargs): super().__init__(description, kwargs.get('choices', []), yielding=kwargs.get('yielding', None)) self.split_args = split_args self.allow_dups = allow_dups self.value = self.validate_value(value, user_input=user_input) - def validate_value(self, value, user_input: bool = True) -> List[str]: + def validate_value(self, value, user_input: bool = True) -> T.List[str]: # User input is for options defined on the command line (via -D # options). Users can put their input in as a comma separated # string, but for defining options in meson_options.txt the format @@ -229,16 +226,16 @@ class UserFeatureOption(UserComboOption): return self.value == 'auto' -def load_configs(filenames: List[str]) -> configparser.ConfigParser: +def load_configs(filenames: T.List[str]) -> configparser.ConfigParser: """Load configuration files from a named subdirectory.""" config = configparser.ConfigParser() config.read(filenames) return config -if TYPE_CHECKING: - CacheKeyType = Tuple[Tuple[Any, ...], ...] - SubCacheKeyType = Tuple[Any, ...] +if T.TYPE_CHECKING: + CacheKeyType = T.Tuple[T.Tuple[T.Any, ...], ...] + SubCacheKeyType = T.Tuple[T.Any, ...] class DependencyCacheType(enum.Enum): @@ -262,7 +259,7 @@ class DependencySubCache: def __init__(self, type_: DependencyCacheType): self.types = [type_] - self.__cache = {} # type: Dict[SubCacheKeyType, dependencies.Dependency] + self.__cache = {} # type: T.Dict[SubCacheKeyType, dependencies.Dependency] def __getitem__(self, key: 'SubCacheKeyType') -> 'dependencies.Dependency': return self.__cache[key] @@ -273,7 +270,7 @@ class DependencySubCache: def __contains__(self, key: 'SubCacheKeyType') -> bool: return key in self.__cache - def values(self) -> Iterable['dependencies.Dependency']: + def values(self) -> T.Iterable['dependencies.Dependency']: return self.__cache.values() @@ -285,12 +282,12 @@ class DependencyCache: successfully lookup by providing a simple get/put interface. """ - def __init__(self, builtins_per_machine: PerMachine[Dict[str, UserOption[Any]]], for_machine: MachineChoice): - self.__cache = OrderedDict() # type: MutableMapping[CacheKeyType, DependencySubCache] + def __init__(self, builtins_per_machine: PerMachine[T.Dict[str, UserOption[T.Any]]], for_machine: MachineChoice): + self.__cache = OrderedDict() # type: T.MutableMapping[CacheKeyType, DependencySubCache] self.__builtins_per_machine = builtins_per_machine self.__for_machine = for_machine - def __calculate_subkey(self, type_: DependencyCacheType) -> Tuple[Any, ...]: + def __calculate_subkey(self, type_: DependencyCacheType) -> T.Tuple[T.Any, ...]: if type_ is DependencyCacheType.PKG_CONFIG: return tuple(self.__builtins_per_machine[self.__for_machine]['pkg_config_path'].value) elif type_ is DependencyCacheType.CMAKE: @@ -298,7 +295,7 @@ class DependencyCache: assert type_ is DependencyCacheType.OTHER, 'Someone forgot to update subkey calculations for a new type' return tuple() - def __iter__(self) -> Iterator['CacheKeyType']: + def __iter__(self) -> T.Iterator['CacheKeyType']: return self.keys() def put(self, key: 'CacheKeyType', dep: 'dependencies.Dependency') -> None: @@ -308,7 +305,7 @@ class DependencyCache: subkey = self.__calculate_subkey(t) self.__cache[key][subkey] = dep - def get(self, key: 'CacheKeyType') -> Optional['dependencies.Dependency']: + def get(self, key: 'CacheKeyType') -> T.Optional['dependencies.Dependency']: """Get a value from the cache. If there is no cache entry then None will be returned. @@ -326,14 +323,14 @@ class DependencyCache: pass return None - def values(self) -> Iterator['dependencies.Dependency']: + def values(self) -> T.Iterator['dependencies.Dependency']: for c in self.__cache.values(): yield from c.values() - def keys(self) -> Iterator['CacheKeyType']: + def keys(self) -> T.Iterator['CacheKeyType']: return iter(self.__cache.keys()) - def items(self) -> Iterator[Tuple['CacheKeyType', List['dependencies.Dependency']]]: + def items(self) -> T.Iterator[T.Tuple['CacheKeyType', T.List['dependencies.Dependency']]]: for k, v in self.__cache.items(): vs = [] for t in v.types: @@ -346,7 +343,7 @@ class DependencyCache: self.__cache.clear() # Can't bind this near the class method it seems, sadly. -_V = TypeVar('_V') +_V = T.TypeVar('_V') # This class contains all data that must persist over multiple # invocations of Meson. It is roughly the same thing as @@ -368,10 +365,10 @@ class CoreData: self.target_guids = {} self.version = version self.init_builtins() - self.backend_options = {} # : Dict[str, UserOption] - self.user_options = {} # : Dict[str, UserOption] + self.backend_options = {} # : T.Dict[str, UserOption] + self.user_options = {} # : T.Dict[str, UserOption] self.compiler_options = PerMachine({}, {}) - self.base_options = {} # : Dict[str, UserOption] + self.base_options = {} # : T.Dict[str, UserOption] self.cross_files = self.__load_config_files(options, scratch_dir, 'cross') self.compilers = PerMachine(OrderedDict(), OrderedDict()) @@ -384,7 +381,7 @@ class CoreData: self.libdir_cross_fixup() @staticmethod - def __load_config_files(options: argparse.Namespace, scratch_dir: str, ftype: str) -> List[str]: + def __load_config_files(options: argparse.Namespace, scratch_dir: str, ftype: str) -> T.List[str]: # Need to try and make the passed filenames absolute because when the # files are parsed later we'll have chdir()d. if ftype == 'cross': @@ -395,9 +392,9 @@ class CoreData: if not filenames: return [] - found_invalid = [] # type: List[str] - missing = [] # type: List[str] - real = [] # type: List[str] + found_invalid = [] # type: T.List[str] + missing = [] # type: T.List[str] + real = [] # type: T.List[str] for i, f in enumerate(filenames): f = os.path.expanduser(os.path.expandvars(f)) if os.path.exists(f): @@ -591,8 +588,8 @@ class CoreData: @staticmethod def get_prefixed_options_per_machine( - options_per_machine # : PerMachine[Dict[str, _V]]] - ) -> Iterable[Dict[str, _V]]: + options_per_machine # : PerMachine[T.Dict[str, _V]]] + ) -> T.Iterable[T.Dict[str, _V]]: for for_machine in iter(MachineChoice): prefix = for_machine.get_prefix() yield { @@ -600,17 +597,17 @@ class CoreData: for k, v in options_per_machine[for_machine].items() } - def _get_all_nonbuiltin_options(self) -> Iterable[Dict[str, UserOption]]: + def _get_all_nonbuiltin_options(self) -> T.Iterable[T.Dict[str, UserOption]]: yield self.backend_options yield self.user_options yield from self.get_prefixed_options_per_machine(self.compiler_options) yield self.base_options - def _get_all_builtin_options(self) -> Dict[str, UserOption]: + def _get_all_builtin_options(self) -> T.Dict[str, UserOption]: yield from self.get_prefixed_options_per_machine(self.builtins_per_machine) yield self.builtins - def get_all_options(self) -> Dict[str, UserOption]: + def get_all_options(self) -> T.Dict[str, UserOption]: yield from self._get_all_nonbuiltin_options() yield from self._get_all_builtin_options() @@ -744,7 +741,7 @@ class CoreData: self.set_options(options, subproject=subproject) - def add_lang_args(self, lang: str, comp: Type['Compiler'], + def add_lang_args(self, lang: str, comp: T.Type['Compiler'], for_machine: MachineChoice, env: 'Environment') -> None: """Add global language arguments that are needed before compiler/linker detection.""" from .compilers import compilers @@ -759,7 +756,7 @@ class CoreData: o.set_value(env.cmd_line_options[opt_prefix + k]) self.compiler_options[for_machine].setdefault(k, o) - def process_new_compiler(self, lang: str, comp: Type['Compiler'], env: 'Environment') -> None: + def process_new_compiler(self, lang: str, comp: T.Type['Compiler'], env: 'Environment') -> None: from . import compilers self.compilers[comp.for_machine][lang] = comp @@ -934,17 +931,17 @@ def parse_cmd_line_options(args): delattr(args, name) -_U = TypeVar('_U', bound=UserOption[_T]) +_U = T.TypeVar('_U', bound=UserOption[_T]) -class BuiltinOption(Generic[_T, _U]): +class BuiltinOption(T.Generic[_T, _U]): """Class for a builtin option type. Currently doesn't support UserIntegerOption, or a few other cases. """ - def __init__(self, opt_type: Type[_U], description: str, default: Any, yielding: Optional[bool] = None, *, - choices: Any = None): + def __init__(self, opt_type: T.Type[_U], description: str, default: T.Any, yielding: T.Optional[bool] = None, *, + choices: T.Any = None): self.opt_type = opt_type self.description = description self.default = default @@ -958,14 +955,14 @@ class BuiltinOption(Generic[_T, _U]): keywords['choices'] = self.choices return self.opt_type(self.description, **keywords) - def _argparse_action(self) -> Optional[str]: + def _argparse_action(self) -> T.Optional[str]: if self.default is True: return 'store_false' elif self.default is False: return 'store_true' return None - def _argparse_choices(self) -> Any: + def _argparse_choices(self) -> T.Any: if self.opt_type is UserBooleanOption: return [True, False] elif self.opt_type is UserFeatureOption: @@ -979,7 +976,7 @@ class BuiltinOption(Generic[_T, _U]): else: return '--' + name.replace('_', '-') - def prefixed_default(self, name: str, prefix: str = '') -> Any: + def prefixed_default(self, name: str, prefix: str = '') -> T.Any: if self.opt_type in [UserComboOption, UserIntegerOption]: return self.default try: @@ -1042,8 +1039,8 @@ builtin_options = OrderedDict([ ]) builtin_options_per_machine = OrderedDict([ - ('pkg_config_path', BuiltinOption(UserArrayOption, 'List of additional paths for pkg-config to search', [])), - ('cmake_prefix_path', BuiltinOption(UserArrayOption, 'List of additional prefixes for cmake to search', [])), + ('pkg_config_path', BuiltinOption(UserArrayOption, 'T.List of additional paths for pkg-config to search', [])), + ('cmake_prefix_path', BuiltinOption(UserArrayOption, 'T.List of additional prefixes for cmake to search', [])), ]) # Special prefix-dependent defaults for installation directories that reside in diff --git a/mesonbuild/dependencies/base.py b/mesonbuild/dependencies/base.py index f17b9f2..e510934 100644 --- a/mesonbuild/dependencies/base.py +++ b/mesonbuild/dependencies/base.py @@ -24,7 +24,7 @@ import shutil import stat import textwrap import platform -from typing import Any, Dict, List, Optional, Tuple, Type, Union +import typing as T from enum import Enum from pathlib import Path, PurePath @@ -127,7 +127,7 @@ class Dependency: self.sources = [] self.methods = self._process_method_kw(kwargs) self.include_type = self._process_include_type_kw(kwargs) - self.ext_deps = [] # type: List[Dependency] + self.ext_deps = [] # type: T.List[Dependency] def __repr__(self): s = '<{0} {1}: {2}>' @@ -152,7 +152,7 @@ class Dependency: return converted return self.compile_args - def get_link_args(self, raw: bool = False) -> List[str]: + def get_link_args(self, raw: bool = False) -> T.List[str]: if raw and self.raw_link_args is not None: return self.raw_link_args return self.link_args @@ -208,8 +208,8 @@ class Dependency: """ raise RuntimeError('Unreachable code in partial_dependency called') - def _add_sub_dependency(self, dep_type: Type['Dependency'], env: Environment, - kwargs: Dict[str, Any], *, + def _add_sub_dependency(self, dep_type: T.Type['Dependency'], env: Environment, + kwargs: T.Dict[str, T.Any], *, method: DependencyMethods = DependencyMethods.AUTO) -> None: """Add an internal dependency of of the given type. @@ -222,14 +222,14 @@ class Dependency: kwargs['method'] = method self.ext_deps.append(dep_type(env, kwargs)) - def get_variable(self, *, cmake: Optional[str] = None, pkgconfig: Optional[str] = None, - configtool: Optional[str] = None, default_value: Optional[str] = None, - pkgconfig_define: Optional[List[str]] = None) -> Union[str, List[str]]: + def get_variable(self, *, cmake: T.Optional[str] = None, pkgconfig: T.Optional[str] = None, + configtool: T.Optional[str] = None, default_value: T.Optional[str] = None, + pkgconfig_define: T.Optional[T.List[str]] = None) -> T.Union[str, T.List[str]]: if default_value is not None: return default_value raise DependencyException('No default provided for dependency {!r}, which is not pkg-config, cmake, or config-tool based.'.format(self)) - def generate_system_dependency(self, include_type: str) -> Type['Dependency']: + def generate_system_dependency(self, include_type: str) -> T.Type['Dependency']: new_dep = copy.deepcopy(self) new_dep.include_type = self._process_include_type_kw({'include_type': include_type}) return new_dep @@ -553,9 +553,9 @@ class ConfigToolDependency(ExternalDependency): def log_tried(self): return self.type_name - def get_variable(self, *, cmake: Optional[str] = None, pkgconfig: Optional[str] = None, - configtool: Optional[str] = None, default_value: Optional[str] = None, - pkgconfig_define: Optional[List[str]] = None) -> Union[str, List[str]]: + def get_variable(self, *, cmake: T.Optional[str] = None, pkgconfig: T.Optional[str] = None, + configtool: T.Optional[str] = None, default_value: T.Optional[str] = None, + pkgconfig_define: T.Optional[T.List[str]] = None) -> T.Union[str, T.List[str]]: if configtool: # In the not required case '' (empty string) will be returned if the # variable is not found. Since '' is a valid value to return we @@ -704,7 +704,7 @@ class PkgConfigDependency(ExternalDependency): cache[(self.pkgbin, targs, fenv)] = self._call_pkgbin_real(args, env) return cache[(self.pkgbin, targs, fenv)] - def _convert_mingw_paths(self, args: List[str]) -> List[str]: + def _convert_mingw_paths(self, args: T.List[str]) -> T.List[str]: ''' Both MSVC and native Python on Windows cannot handle MinGW-esque /c/foo paths so convert them to C:/foo. We cannot resolve other paths starting @@ -1006,9 +1006,9 @@ class PkgConfigDependency(ExternalDependency): def log_tried(self): return self.type_name - def get_variable(self, *, cmake: Optional[str] = None, pkgconfig: Optional[str] = None, - configtool: Optional[str] = None, default_value: Optional[str] = None, - pkgconfig_define: Optional[List[str]] = None) -> Union[str, List[str]]: + def get_variable(self, *, cmake: T.Optional[str] = None, pkgconfig: T.Optional[str] = None, + configtool: T.Optional[str] = None, default_value: T.Optional[str] = None, + pkgconfig_define: T.Optional[T.List[str]] = None) -> T.Union[str, T.List[str]]: if pkgconfig: kwargs = {} if default_value is not None: @@ -1039,10 +1039,10 @@ class CMakeDependency(ExternalDependency): def _main_cmake_file(self) -> str: return 'CMakeLists.txt' - def _extra_cmake_opts(self) -> List[str]: + def _extra_cmake_opts(self) -> T.List[str]: return [] - def _map_module_list(self, modules: List[Tuple[str, bool]]) -> List[Tuple[str, bool]]: + def _map_module_list(self, modules: T.List[T.Tuple[str, bool]]) -> T.List[T.Tuple[str, bool]]: # Map the input module list to something else # This function will only be executed AFTER the initial CMake # interpreter pass has completed. Thus variables defined in the @@ -1083,7 +1083,7 @@ class CMakeDependency(ExternalDependency): # Where all CMake "build dirs" are located self.cmake_root_dir = environment.scratch_dir - # List of successfully found modules + # T.List of successfully found modules self.found_modules = [] self.cmakebin = CMakeExecutor(environment, CMakeDependency.class_cmake_version, self.for_machine, silent=self.silent) @@ -1203,7 +1203,7 @@ class CMakeDependency(ExternalDependency): @staticmethod @functools.lru_cache(maxsize=None) - def _cached_listdir(path: str) -> Tuple[Tuple[str, str]]: + def _cached_listdir(path: str) -> T.Tuple[T.Tuple[str, str]]: try: return tuple((x, str(x).lower()) for x in os.listdir(path)) except OSError: @@ -1217,7 +1217,7 @@ class CMakeDependency(ExternalDependency): except OSError: return False - def _preliminary_find_check(self, name: str, module_path: List[str], prefix_path: List[str], machine: MachineInfo) -> bool: + def _preliminary_find_check(self, name: str, module_path: T.List[str], prefix_path: T.List[str], machine: MachineInfo) -> bool: lname = str(name).lower() # Checks , /cmake, /CMake @@ -1295,7 +1295,7 @@ class CMakeDependency(ExternalDependency): return False - def _detect_dep(self, name: str, modules: List[Tuple[str, bool]], args: List[str]): + def _detect_dep(self, name: str, modules: T.List[T.Tuple[str, bool]], args: T.List[str]): # Detect a dependency with CMake using the '--find-package' mode # and the trace output (stderr) # @@ -1410,7 +1410,7 @@ class CMakeDependency(ExternalDependency): for i, required in modules: if i not in self.traceparser.targets: if not required: - mlog.warning('CMake: Optional module', mlog.bold(self._original_module_name(i)), 'for', mlog.bold(name), 'was not found') + mlog.warning('CMake: T.Optional module', mlog.bold(self._original_module_name(i)), 'for', mlog.bold(name), 'was not found') continue raise self._gen_exception('CMake: invalid module {} for {}.\n' 'Try to explicitly specify one or more targets with the "modules" property.\n' @@ -1548,9 +1548,9 @@ project(MesonTemp LANGUAGES {}) return 'modules: ' + ', '.join(modules) return '' - def get_variable(self, *, cmake: Optional[str] = None, pkgconfig: Optional[str] = None, - configtool: Optional[str] = None, default_value: Optional[str] = None, - pkgconfig_define: Optional[List[str]] = None) -> Union[str, List[str]]: + def get_variable(self, *, cmake: T.Optional[str] = None, pkgconfig: T.Optional[str] = None, + configtool: T.Optional[str] = None, default_value: T.Optional[str] = None, + pkgconfig_define: T.Optional[T.List[str]] = None) -> T.Union[str, T.List[str]]: if cmake: try: v = self.traceparser.vars[cmake] @@ -1765,9 +1765,9 @@ class ExternalProgram: # An 'ExternalProgram' always runs on the build machine for_machine = MachineChoice.BUILD - def __init__(self, name: str, command: Optional[List[str]] = None, - silent: bool = False, search_dir: Optional[str] = None, - extra_search_dirs: Optional[List[str]] = None): + def __init__(self, name: str, command: T.Optional[T.List[str]] = None, + silent: bool = False, search_dir: T.Optional[str] = None, + extra_search_dirs: T.Optional[T.List[str]] = None): self.name = name if command is not None: self.command = listify(command) @@ -2153,7 +2153,7 @@ class ExtraFrameworkDependency(ExternalDependency): return 'framework' -def get_dep_identifier(name, kwargs) -> Tuple: +def get_dep_identifier(name, kwargs) -> T.Tuple: identifier = (name, ) for key, value in kwargs.items(): # 'version' is irrelevant for caching; the caller must check version matches @@ -2267,7 +2267,7 @@ def find_external_dependency(name, env, kwargs): return NotFoundDependency(env) -def _build_external_dependency_list(name, env: Environment, kwargs: Dict[str, Any]) -> list: +def _build_external_dependency_list(name, env: Environment, kwargs: T.Dict[str, T.Any]) -> list: # First check if the method is valid if 'method' in kwargs and kwargs['method'] not in [e.value for e in DependencyMethods]: raise DependencyException('method {!r} is invalid'.format(kwargs['method'])) @@ -2324,7 +2324,7 @@ def _build_external_dependency_list(name, env: Environment, kwargs: Dict[str, An return candidates -def sort_libpaths(libpaths: List[str], refpaths: List[str]) -> List[str]: +def sort_libpaths(libpaths: T.List[str], refpaths: T.List[str]) -> T.List[str]: """Sort according to It is intended to be used to sort -L flags returned by pkg-config. diff --git a/mesonbuild/dependencies/dev.py b/mesonbuild/dependencies/dev.py index 15907d4..def2adf 100644 --- a/mesonbuild/dependencies/dev.py +++ b/mesonbuild/dependencies/dev.py @@ -29,7 +29,7 @@ from .base import ( ) from .misc import ThreadDependency -from typing import List, Tuple +import typing as T def get_shared_library_suffix(environment, for_machine: MachineChoice): @@ -407,10 +407,10 @@ class LLVMDependencyCMake(CMakeDependency): # Use a custom CMakeLists.txt for LLVM return 'CMakeListsLLVM.txt' - def _extra_cmake_opts(self) -> List[str]: + def _extra_cmake_opts(self) -> T.List[str]: return ['-DLLVM_MESON_MODULES={}'.format(';'.join(self.llvm_modules + self.llvm_opt_modules))] - def _map_module_list(self, modules: List[Tuple[str, bool]]) -> List[Tuple[str, bool]]: + def _map_module_list(self, modules: T.List[T.Tuple[str, bool]]) -> T.List[T.Tuple[str, bool]]: res = [] for mod, required in modules: cm_targets = self.traceparser.get_cmake_var('MESON_LLVM_TARGETS_{}'.format(mod)) diff --git a/mesonbuild/dependencies/mpi.py b/mesonbuild/dependencies/mpi.py index bc0653c..0754712 100644 --- a/mesonbuild/dependencies/mpi.py +++ b/mesonbuild/dependencies/mpi.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import typing +import typing as T import os import re import subprocess @@ -118,7 +118,7 @@ class MPIDependency(ExternalDependency): self.version, self.compile_args, self.link_args = result return - def _filter_compile_args(self, args: typing.Sequence[str]) -> typing.List[str]: + def _filter_compile_args(self, args: T.Sequence[str]) -> T.List[str]: """ MPI wrappers return a bunch of garbage args. Drop -O2 and everything that is not needed. @@ -142,7 +142,7 @@ class MPIDependency(ExternalDependency): result.append(f) return result - def _filter_link_args(self, args: typing.Sequence[str], cid: str) -> typing.List[str]: + def _filter_link_args(self, args: T.Sequence[str], cid: str) -> T.List[str]: """ MPI wrappers return a bunch of garbage args. Drop -O2 and everything that is not needed. @@ -210,7 +210,7 @@ class MPIDependency(ExternalDependency): return version, cargs, libs - def _try_other_wrapper(self, prog, cid: str) -> typing.Tuple[str, typing.List[str], typing.List[str]]: + def _try_other_wrapper(self, prog, cid: str) -> T.Tuple[str, T.List[str], T.List[str]]: prog = ExternalProgram(prog, silent=True) if not prog.found(): return None @@ -243,7 +243,7 @@ class MPIDependency(ExternalDependency): return version, args, args - def _try_msmpi(self) -> typing.Tuple[str, typing.List[str], typing.List[str]]: + def _try_msmpi(self) -> T.Tuple[str, T.List[str], T.List[str]]: if self.language == 'cpp': # MS-MPI does not support the C++ version of MPI, only the standard C API. return None diff --git a/mesonbuild/envconfig.py b/mesonbuild/envconfig.py index 0f277a7..98644c0 100644 --- a/mesonbuild/envconfig.py +++ b/mesonbuild/envconfig.py @@ -13,13 +13,13 @@ # limitations under the License. import configparser, os, subprocess -import typing +import typing as T from . import mesonlib from .mesonlib import EnvironmentException, split_args from . import mlog -_T = typing.TypeVar('_T') +_T = T.TypeVar('_T') # These classes contains all the data pulled from configuration files (native @@ -77,7 +77,7 @@ CPU_FAMILES_64_BIT = [ class MesonConfigFile: @classmethod - def from_config_parser(cls, parser: configparser.ConfigParser) -> typing.Dict[str, typing.Dict[str, typing.Dict[str, str]]]: + def from_config_parser(cls, parser: configparser.ConfigParser) -> T.Dict[str, T.Dict[str, T.Dict[str, str]]]: out = {} # This is a bit hackish at the moment. for s in parser.sections(): @@ -120,10 +120,10 @@ class HasEnvVarFallback: class Properties(HasEnvVarFallback): def __init__( self, - properties: typing.Optional[typing.Dict[str, typing.Union[str, typing.List[str]]]] = None, + properties: T.Optional[T.Dict[str, T.Union[str, T.List[str]]]] = None, fallback: bool = True): super().__init__(fallback) - self.properties = properties or {} # type: typing.Dict[str, typing.Union[str, typing.List[str]]] + self.properties = properties or {} # type: T.Dict[str, T.Union[str, T.List[str]]] def has_stdlib(self, language: str) -> bool: return language + '_stdlib' in self.properties @@ -131,30 +131,30 @@ class Properties(HasEnvVarFallback): # Some of get_stdlib, get_root, get_sys_root are wider than is actually # true, but without heterogenious dict annotations it's not practical to # narrow them - def get_stdlib(self, language: str) -> typing.Union[str, typing.List[str]]: + def get_stdlib(self, language: str) -> T.Union[str, T.List[str]]: return self.properties[language + '_stdlib'] - def get_root(self) -> typing.Optional[typing.Union[str, typing.List[str]]]: + def get_root(self) -> T.Optional[T.Union[str, T.List[str]]]: return self.properties.get('root', None) - def get_sys_root(self) -> typing.Optional[typing.Union[str, typing.List[str]]]: + def get_sys_root(self) -> T.Optional[T.Union[str, T.List[str]]]: return self.properties.get('sys_root', None) - def __eq__(self, other: typing.Any) -> 'typing.Union[bool, NotImplemented]': + def __eq__(self, other: T.Any) -> 'T.Union[bool, NotImplemented]': if isinstance(other, type(self)): return self.properties == other.properties return NotImplemented # TODO consider removing so Properties is less freeform - def __getitem__(self, key: str) -> typing.Any: + def __getitem__(self, key: str) -> T.Any: return self.properties[key] # TODO consider removing so Properties is less freeform - def __contains__(self, item: typing.Any) -> bool: + def __contains__(self, item: T.Any) -> bool: return item in self.properties # TODO consider removing, for same reasons as above - def get(self, key: str, default: typing.Any = None) -> typing.Any: + def get(self, key: str, default: T.Any = None) -> T.Any: return self.properties.get(key, default) class MachineInfo: @@ -165,7 +165,7 @@ class MachineInfo: self.endian = endian self.is_64_bit = cpu_family in CPU_FAMILES_64_BIT # type: bool - def __eq__(self, other: typing.Any) -> 'typing.Union[bool, NotImplemented]': + def __eq__(self, other: T.Any) -> 'T.Union[bool, NotImplemented]': if self.__class__ is not other.__class__: return NotImplemented return \ @@ -174,7 +174,7 @@ class MachineInfo: self.cpu == other.cpu and \ self.endian == other.endian - def __ne__(self, other: typing.Any) -> 'typing.Union[bool, NotImplemented]': + def __ne__(self, other: T.Any) -> 'T.Union[bool, NotImplemented]': if self.__class__ is not other.__class__: return NotImplemented return not self.__eq__(other) @@ -183,7 +183,7 @@ class MachineInfo: return ''.format(self.system, self.cpu_family, self.cpu) @classmethod - def from_literal(cls, literal: typing.Dict[str, str]) -> 'MachineInfo': + def from_literal(cls, literal: T.Dict[str, str]) -> 'MachineInfo': minimum_literal = {'cpu', 'cpu_family', 'endian', 'system'} if set(literal) < minimum_literal: raise EnvironmentException( @@ -281,10 +281,10 @@ class MachineInfo: class BinaryTable(HasEnvVarFallback): def __init__( self, - binaries: typing.Optional[typing.Dict[str, typing.Union[str, typing.List[str]]]] = None, + binaries: T.Optional[T.Dict[str, T.Union[str, T.List[str]]]] = None, fallback: bool = True): super().__init__(fallback) - self.binaries = binaries or {} # type: typing.Dict[str, typing.Union[str, typing.List[str]]] + self.binaries = binaries or {} # type: T.Dict[str, T.Union[str, T.List[str]]] for name, command in self.binaries.items(): if not isinstance(command, (list, str)): # TODO generalize message @@ -315,10 +315,10 @@ class BinaryTable(HasEnvVarFallback): 'cmake': 'CMAKE', 'qmake': 'QMAKE', 'pkgconfig': 'PKG_CONFIG', - } # type: typing.Dict[str, str] + } # type: T.Dict[str, str] @staticmethod - def detect_ccache() -> typing.List[str]: + def detect_ccache() -> T.List[str]: try: subprocess.check_call(['ccache', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) except (OSError, subprocess.CalledProcessError): @@ -333,7 +333,7 @@ class BinaryTable(HasEnvVarFallback): This is probably wrong, it should always point to the native compiler.''' % evar) @classmethod - def parse_entry(cls, entry: typing.Union[str, typing.List[str]]) -> typing.Tuple[typing.List[str], typing.List[str]]: + def parse_entry(cls, entry: T.Union[str, T.List[str]]) -> T.Tuple[T.List[str], T.List[str]]: compiler = mesonlib.stringlistify(entry) # Ensure ccache exists and remove it if it doesn't if compiler[0] == 'ccache': @@ -344,7 +344,7 @@ This is probably wrong, it should always point to the native compiler.''' % evar # Return value has to be a list of compiler 'choices' return compiler, ccache - def lookup_entry(self, name: str) -> typing.Optional[typing.List[str]]: + def lookup_entry(self, name: str) -> T.Optional[T.List[str]]: """Lookup binaryk Returns command with args as list if found, Returns `None` if nothing is @@ -377,13 +377,13 @@ class Directories: builds. """ - def __init__(self, bindir: typing.Optional[str] = None, datadir: typing.Optional[str] = None, - includedir: typing.Optional[str] = None, infodir: typing.Optional[str] = None, - libdir: typing.Optional[str] = None, libexecdir: typing.Optional[str] = None, - localedir: typing.Optional[str] = None, localstatedir: typing.Optional[str] = None, - mandir: typing.Optional[str] = None, prefix: typing.Optional[str] = None, - sbindir: typing.Optional[str] = None, sharedstatedir: typing.Optional[str] = None, - sysconfdir: typing.Optional[str] = None): + def __init__(self, bindir: T.Optional[str] = None, datadir: T.Optional[str] = None, + includedir: T.Optional[str] = None, infodir: T.Optional[str] = None, + libdir: T.Optional[str] = None, libexecdir: T.Optional[str] = None, + localedir: T.Optional[str] = None, localstatedir: T.Optional[str] = None, + mandir: T.Optional[str] = None, prefix: T.Optional[str] = None, + sbindir: T.Optional[str] = None, sharedstatedir: T.Optional[str] = None, + sysconfdir: T.Optional[str] = None): self.bindir = bindir self.datadir = datadir self.includedir = includedir @@ -401,12 +401,12 @@ class Directories: def __contains__(self, key: str) -> bool: return hasattr(self, key) - def __getitem__(self, key: str) -> typing.Optional[str]: + def __getitem__(self, key: str) -> T.Optional[str]: # Mypy can't figure out what to do with getattr here, so we'll case for it - return typing.cast(typing.Optional[str], getattr(self, key)) + return T.cast(T.Optional[str], getattr(self, key)) - def __setitem__(self, key: str, value: typing.Optional[str]) -> None: + def __setitem__(self, key: str, value: T.Optional[str]) -> None: setattr(self, key, value) - def __iter__(self) -> typing.Iterator[typing.Tuple[str, str]]: + def __iter__(self) -> T.Iterator[T.Tuple[str, str]]: return iter(self.__dict__.items()) diff --git a/mesonbuild/environment.py b/mesonbuild/environment.py index 77fc1ae..3d4f49a 100644 --- a/mesonbuild/environment.py +++ b/mesonbuild/environment.py @@ -12,9 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -import os, platform, re, sys, shutil, subprocess, typing +import os, platform, re, sys, shutil, subprocess import tempfile import shlex +import typing as T from . import coredata from .linkers import ArLinker, ArmarLinker, VisualStudioLinker, DLinker, CcrxLinker, IntelVisualStudioLinker @@ -110,7 +111,7 @@ from .compilers import ( build_filename = 'meson.build' -CompilersDict = typing.Dict[str, Compiler] +CompilersDict = T.Dict[str, Compiler] def detect_gcovr(min_version='3.3', new_rootdir_version='4.2', log=False): gcovr_exe = 'gcovr' @@ -167,7 +168,7 @@ def detect_ninja_command_and_version(version: str = '1.5', log: bool = False) -> mlog.log('Found {}-{} at {}'.format(name, found, quote_arg(n))) return (n, found) -def get_llvm_tool_names(tool: str) -> typing.List[str]: +def get_llvm_tool_names(tool: str) -> T.List[str]: # Ordered list of possible suffixes of LLVM executables to try. Start with # base, then try newest back to oldest (3.5 is arbitrary), and finally the # devel version. Please note that the development snapshot in Debian does @@ -194,7 +195,7 @@ def get_llvm_tool_names(tool: str) -> typing.List[str]: names.append(tool + suffix) return names -def detect_scanbuild() -> typing.List[str]: +def detect_scanbuild() -> T.List[str]: """ Look for scan-build binary on build platform First, if a SCANBUILD env variable has been provided, give it precedence @@ -225,7 +226,7 @@ def detect_scanbuild() -> typing.List[str]: return [tool] return [] -def detect_clangformat() -> typing.List[str]: +def detect_clangformat() -> T.List[str]: """ Look for clang-format binary on build platform Do the same thing as detect_scanbuild to find clang-format except it @@ -397,7 +398,7 @@ def detect_msys2_arch(): return os.environ['MSYSTEM_CARCH'] return None -def detect_machine_info(compilers: typing.Optional[CompilersDict] = None) -> MachineInfo: +def detect_machine_info(compilers: T.Optional[CompilersDict] = None) -> MachineInfo: """Detect the machine we're running on If compilers are not provided, we cannot know as much. None out those @@ -732,7 +733,7 @@ class Environment: errmsg += '\nRunning "{0}" gave "{1}"'.format(c, e) raise EnvironmentException(errmsg) - def _guess_win_linker(self, compiler: typing.List[str], comp_class: Compiler, + def _guess_win_linker(self, compiler: T.List[str], comp_class: Compiler, for_machine: MachineChoice, *, use_linker_prefix: bool = True) -> 'DynamicLinker': self.coredata.add_lang_args(comp_class.language, comp_class, for_machine, self) @@ -747,7 +748,7 @@ class Environment: check_args += self.coredata.compiler_options[for_machine][comp_class.language + '_args'].value - override = [] # type: typing.List[str] + override = [] # type: T.List[str] value = self.binaries[for_machine].lookup_entry('ld') if value is not None: override = comp_class.use_linker_args(value[0]) @@ -791,9 +792,9 @@ class Environment: "%PATH% variable to resolve this.") raise EnvironmentException('Unable to determine dynamic linker') - def _guess_nix_linker(self, compiler: typing.List[str], comp_class: typing.Type[Compiler], + def _guess_nix_linker(self, compiler: T.List[str], comp_class: T.Type[Compiler], for_machine: MachineChoice, *, - extra_args: typing.Optional[typing.List[str]] = None) -> 'DynamicLinker': + extra_args: T.Optional[T.List[str]] = None) -> 'DynamicLinker': """Helper for guessing what linker to use on Unix-Like OSes. :compiler: Invocation to use to get linker @@ -802,7 +803,7 @@ class Environment: :extra_args: Any additional arguments required (such as a source file) """ self.coredata.add_lang_args(comp_class.language, comp_class, for_machine, self) - extra_args = typing.cast(typing.List[str], extra_args or []) + extra_args = T.cast(T.List[str], extra_args or []) extra_args += self.coredata.compiler_options[for_machine][comp_class.language + '_args'].value if isinstance(comp_class.LINKER_PREFIX, str): @@ -810,7 +811,7 @@ class Environment: else: check_args = comp_class.LINKER_PREFIX + ['--version'] + extra_args - override = [] # type: typing.List[str] + override = [] # type: T.List[str] value = self.binaries[for_machine].lookup_entry('ld') if value is not None: override = comp_class.use_linker_args(value[0]) diff --git a/mesonbuild/interpreter.py b/mesonbuild/interpreter.py index 14dfddd..4dfb8b3 100644 --- a/mesonbuild/interpreter.py +++ b/mesonbuild/interpreter.py @@ -41,7 +41,7 @@ import subprocess import collections from itertools import chain import functools -from typing import Sequence, List, Union, Optional, Dict, Any +import typing as T import importlib @@ -914,10 +914,10 @@ class RunTargetHolder(TargetHolder): return r.format(self.__class__.__name__, h.get_id(), h.command) class Test(InterpreterObject): - def __init__(self, name: str, project: str, suite: List[str], exe: build.Executable, - depends: List[Union[build.CustomTarget, build.BuildTarget]], - is_parallel: bool, cmd_args: List[str], env: build.EnvironmentVariables, - should_fail: bool, timeout: int, workdir: Optional[str], protocol: str, + def __init__(self, name: str, project: str, suite: T.List[str], exe: build.Executable, + depends: T.List[T.Union[build.CustomTarget, build.BuildTarget]], + is_parallel: bool, cmd_args: T.List[str], env: build.EnvironmentVariables, + should_fail: bool, timeout: int, workdir: T.Optional[str], protocol: str, priority: int): InterpreterObject.__init__(self) self.name = name @@ -2944,7 +2944,7 @@ external dependencies (including libraries) must go to "dependencies".''') self.validate_arguments(args, 0, []) raise Exception() - def add_languages(self, args: Sequence[str], required: bool) -> bool: + def add_languages(self, args: T.Sequence[str], required: bool) -> bool: success = self.add_languages_for(args, required, MachineChoice.BUILD) success &= self.add_languages_for(args, required, MachineChoice.HOST) if not self.coredata.is_cross_build(): @@ -3407,7 +3407,7 @@ external dependencies (including libraries) must go to "dependencies".''') if 'input' not in kwargs or 'output' not in kwargs: raise InterpreterException('Keyword arguments input and output must exist') if 'fallback' not in kwargs: - FeatureNew('Optional fallback in vcs_tag', '0.41.0').use(self.subproject) + FeatureNew('T.Optional fallback in vcs_tag', '0.41.0').use(self.subproject) fallback = kwargs.pop('fallback', self.project_version) if not isinstance(fallback, str): raise InterpreterException('Keyword argument fallback must be a string.') @@ -4469,7 +4469,7 @@ This will become a hard error in the future.''', location=self.current_node) return varname in self.variables @staticmethod - def machine_from_native_kwarg(kwargs: Dict[str, Any]) -> MachineChoice: + def machine_from_native_kwarg(kwargs: T.Dict[str, T.Any]) -> MachineChoice: native = kwargs.get('native', False) if not isinstance(native, bool): raise InvalidArguments('Argument to "native" must be a boolean.') diff --git a/mesonbuild/linkers.py b/mesonbuild/linkers.py index 051b21c..51c5733 100644 --- a/mesonbuild/linkers.py +++ b/mesonbuild/linkers.py @@ -14,18 +14,18 @@ import abc import os -import typing +import typing as T from . import mesonlib -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from .coredata import OptionDictType from .environment import Environment class StaticLinker: - def __init__(self, exelist: typing.List[str]): + def __init__(self, exelist: T.List[str]): self.exelist = exelist def can_linker_accept_rsp(self) -> bool: @@ -34,55 +34,55 @@ class StaticLinker: """ return mesonlib.is_windows() - def get_base_link_args(self, options: 'OptionDictType') -> typing.List[str]: + def get_base_link_args(self, options: 'OptionDictType') -> T.List[str]: """Like compilers.get_base_link_args, but for the static linker.""" return [] - def get_exelist(self) -> typing.List[str]: + def get_exelist(self) -> T.List[str]: return self.exelist.copy() - def get_std_link_args(self) -> typing.List[str]: + def get_std_link_args(self) -> T.List[str]: return [] - def get_buildtype_linker_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_linker_args(self, buildtype: str) -> T.List[str]: return [] - def get_output_args(self, target: str) -> typing.List[str]: + def get_output_args(self, target: str) -> T.List[str]: return[] - def get_coverage_link_args(self) -> typing.List[str]: + def get_coverage_link_args(self) -> T.List[str]: return [] def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str, rpath_paths: str, build_rpath: str, - install_rpath: str) -> typing.List[str]: + install_rpath: str) -> T.List[str]: return [] - def thread_link_flags(self, env: 'Environment') -> typing.List[str]: + def thread_link_flags(self, env: 'Environment') -> T.List[str]: return [] - def openmp_flags(self) -> typing.List[str]: + def openmp_flags(self) -> T.List[str]: return [] - def get_option_link_args(self, options: 'OptionDictType') -> typing.List[str]: + def get_option_link_args(self, options: 'OptionDictType') -> T.List[str]: return [] @classmethod - def unix_args_to_native(cls, args: typing.List[str]) -> typing.List[str]: + def unix_args_to_native(cls, args: T.List[str]) -> T.List[str]: return args[:] @classmethod - def native_args_to_unix(cls, args: typing.List[str]) -> typing.List[str]: + def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]: return args[:] - def get_link_debugfile_args(self, targetfile: str) -> typing.List[str]: + def get_link_debugfile_args(self, targetfile: str) -> T.List[str]: # Static libraries do not have PDB files return [] - def get_always_args(self) -> typing.List[str]: + def get_always_args(self) -> T.List[str]: return [] - def get_linker_always_args(self) -> typing.List[str]: + def get_linker_always_args(self) -> T.List[str]: return [] @@ -92,26 +92,26 @@ class VisualStudioLikeLinker: def __init__(self, machine: str): self.machine = machine - def get_always_args(self) -> typing.List[str]: + def get_always_args(self) -> T.List[str]: return self.always_args.copy() - def get_linker_always_args(self) -> typing.List[str]: + def get_linker_always_args(self) -> T.List[str]: return self.always_args.copy() - def get_output_args(self, target: str) -> typing.List[str]: - args = [] # type: typing.List[str] + def get_output_args(self, target: str) -> T.List[str]: + args = [] # type: T.List[str] if self.machine: args += ['/MACHINE:' + self.machine] args += ['/OUT:' + target] return args @classmethod - def unix_args_to_native(cls, args: typing.List[str]) -> typing.List[str]: + def unix_args_to_native(cls, args: T.List[str]) -> T.List[str]: from .compilers import VisualStudioCCompiler return VisualStudioCCompiler.unix_args_to_native(args) @classmethod - def native_args_to_unix(cls, args: typing.List[str]) -> typing.List[str]: + def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]: from .compilers import VisualStudioCCompiler return VisualStudioCCompiler.native_args_to_unix(args) @@ -120,7 +120,7 @@ class VisualStudioLinker(VisualStudioLikeLinker, StaticLinker): """Microsoft's lib static linker.""" - def __init__(self, exelist: typing.List[str], machine: str): + def __init__(self, exelist: T.List[str], machine: str): StaticLinker.__init__(self, exelist) VisualStudioLikeLinker.__init__(self, machine) @@ -129,14 +129,14 @@ class IntelVisualStudioLinker(VisualStudioLikeLinker, StaticLinker): """Intel's xilib static linker.""" - def __init__(self, exelist: typing.List[str], machine: str): + def __init__(self, exelist: T.List[str], machine: str): StaticLinker.__init__(self, exelist) VisualStudioLikeLinker.__init__(self, machine) class ArLinker(StaticLinker): - def __init__(self, exelist: typing.List[str]): + def __init__(self, exelist: T.List[str]): super().__init__(exelist) self.id = 'ar' pc, stdo = mesonlib.Popen_safe(self.exelist + ['-h'])[0:2] @@ -146,16 +146,16 @@ class ArLinker(StaticLinker): else: self.std_args = ['csr'] - def get_std_link_args(self) -> typing.List[str]: + def get_std_link_args(self) -> T.List[str]: return self.std_args - def get_output_args(self, target: str) -> typing.List[str]: + def get_output_args(self, target: str) -> T.List[str]: return [target] class ArmarLinker(ArLinker): # lgtm [py/missing-call-to-init] - def __init__(self, exelist: typing.List[str]): + def __init__(self, exelist: T.List[str]): StaticLinker.__init__(self, exelist) self.id = 'armar' self.std_args = ['-csr'] @@ -166,18 +166,18 @@ class ArmarLinker(ArLinker): # lgtm [py/missing-call-to-init] class DLinker(StaticLinker): - def __init__(self, exelist: typing.List[str], arch: str): + def __init__(self, exelist: T.List[str], arch: str): super().__init__(exelist) self.id = exelist[0] self.arch = arch - def get_std_link_args(self) -> typing.List[str]: + def get_std_link_args(self) -> T.List[str]: return ['-lib'] - def get_output_args(self, target: str) -> typing.List[str]: + def get_output_args(self, target: str) -> T.List[str]: return ['-of=' + target] - def get_linker_always_args(self) -> typing.List[str]: + def get_linker_always_args(self) -> T.List[str]: if mesonlib.is_windows(): if self.arch == 'x86_64': return ['-m64'] @@ -189,21 +189,21 @@ class DLinker(StaticLinker): class CcrxLinker(StaticLinker): - def __init__(self, exelist: typing.List[str]): + def __init__(self, exelist: T.List[str]): super().__init__(exelist) self.id = 'rlink' def can_linker_accept_rsp(self) -> bool: return False - def get_output_args(self, target: str) -> typing.List[str]: + def get_output_args(self, target: str) -> T.List[str]: return ['-output=%s' % target] - def get_linker_always_args(self) -> typing.List[str]: + def get_linker_always_args(self) -> T.List[str]: return ['-nologo', '-form=library'] -def prepare_rpaths(raw_rpaths: str, build_dir: str, from_dir: str) -> typing.List[str]: +def prepare_rpaths(raw_rpaths: str, build_dir: str, from_dir: str) -> T.List[str]: # The rpaths we write must be relative if they point to the build dir, # because otherwise they have different length depending on the build # directory. This breaks reproducible builds. @@ -212,7 +212,7 @@ def prepare_rpaths(raw_rpaths: str, build_dir: str, from_dir: str) -> typing.Lis return ordered_rpaths -def order_rpaths(rpath_list: typing.List[str]) -> typing.List[str]: +def order_rpaths(rpath_list: T.List[str]) -> T.List[str]: # We want rpaths that point inside our build dir to always override # those pointing to other places in the file system. This is so built # binaries prefer our libraries to the ones that may lie somewhere @@ -244,18 +244,18 @@ class DynamicLinker(metaclass=abc.ABCMeta): 'release': [], 'minsize': [], 'custom': [], - } # type: typing.Dict[str, typing.List[str]] + } # type: T.Dict[str, T.List[str]] - def _apply_prefix(self, arg: str) -> typing.List[str]: + def _apply_prefix(self, arg: str) -> T.List[str]: if self.prefix_arg is None: return [arg] elif isinstance(self.prefix_arg, str): return [self.prefix_arg + arg] return self.prefix_arg + [arg] - def __init__(self, exelist: typing.List[str], for_machine: mesonlib.MachineChoice, - id_: str, prefix_arg: typing.Union[str, typing.List[str]], - always_args: typing.List[str], *, version: str = 'unknown version'): + def __init__(self, exelist: T.List[str], for_machine: mesonlib.MachineChoice, + id_: str, prefix_arg: T.Union[str, T.List[str]], + always_args: T.List[str], *, version: str = 'unknown version'): self.exelist = exelist self.for_machine = for_machine self.version = version @@ -272,14 +272,14 @@ class DynamicLinker(metaclass=abc.ABCMeta): def get_version_string(self) -> str: return '({} {})'.format(self.id, self.version) - def get_exelist(self) -> typing.List[str]: + def get_exelist(self) -> T.List[str]: return self.exelist.copy() def get_accepts_rsp(self) -> bool: # TODO: is it really a matter of is_windows or is it for_windows? return mesonlib.is_windows() - def get_always_args(self) -> typing.List[str]: + def get_always_args(self) -> T.List[str]: return self.always_args.copy() def get_lib_prefix(self) -> str: @@ -287,20 +287,20 @@ class DynamicLinker(metaclass=abc.ABCMeta): # XXX: is use_ldflags a compiler or a linker attribute? - def get_args_from_envvars(self) -> typing.List[str]: + def get_args_from_envvars(self) -> T.List[str]: flags = os.environ.get('LDFLAGS') if not flags: return [] return mesonlib.split_args(flags) - def get_option_args(self, options: 'OptionDictType') -> typing.List[str]: + def get_option_args(self, options: 'OptionDictType') -> T.List[str]: return [] - def has_multi_arguments(self, args: typing.List[str], env: 'Environment') -> typing.Tuple[bool, bool]: + def has_multi_arguments(self, args: T.List[str], env: 'Environment') -> T.Tuple[bool, bool]: m = 'Language {} does not support has_multi_link_arguments.' raise mesonlib.EnvironmentException(m.format(self.id)) - def get_debugfile_args(self, targetfile: str) -> typing.List[str]: + def get_debugfile_args(self, targetfile: str) -> T.List[str]: """Some compilers (MSVC) write debug into a separate file. This method takes the target object path and returns a list of @@ -309,67 +309,67 @@ class DynamicLinker(metaclass=abc.ABCMeta): """ return [] - def get_std_shared_lib_args(self) -> typing.List[str]: + def get_std_shared_lib_args(self) -> T.List[str]: return [] - def get_std_shared_module_args(self, options: 'OptionDictType') -> typing.List[str]: + def get_std_shared_module_args(self, options: 'OptionDictType') -> T.List[str]: return self.get_std_shared_lib_args() - def get_pie_args(self) -> typing.List[str]: + def get_pie_args(self) -> T.List[str]: # TODO: this really needs to take a boolean and return the args to # disable pie, otherwise it only acts to enable pie if pie *isn't* the # default. m = 'Linker {} does not support position-independent executable' raise mesonlib.EnvironmentException(m.format(self.id)) - def get_lto_args(self) -> typing.List[str]: + def get_lto_args(self) -> T.List[str]: return [] - def sanitizer_args(self, value: str) -> typing.List[str]: + def sanitizer_args(self, value: str) -> T.List[str]: return [] - def get_buildtype_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_args(self, buildtype: str) -> T.List[str]: # We can override these in children by just overriding the # _BUILDTYPE_ARGS value. return self._BUILDTYPE_ARGS[buildtype] - def get_asneeded_args(self) -> typing.List[str]: + def get_asneeded_args(self) -> T.List[str]: return [] - def get_link_whole_for(self, args: typing.List[str]) -> typing.List[str]: + def get_link_whole_for(self, args: T.List[str]) -> T.List[str]: raise mesonlib.EnvironmentException( 'Linker {} does not support link_whole'.format(self.id)) - def get_allow_undefined_args(self) -> typing.List[str]: + def get_allow_undefined_args(self) -> T.List[str]: raise mesonlib.EnvironmentException( 'Linker {} does not support allow undefined'.format(self.id)) @abc.abstractmethod - def get_output_args(self, outname: str) -> typing.List[str]: + def get_output_args(self, outname: str) -> T.List[str]: pass - def get_coverage_args(self) -> typing.List[str]: + def get_coverage_args(self) -> T.List[str]: m = "Linker {} doesn't implement coverage data generation.".format(self.id) raise mesonlib.EnvironmentException(m) @abc.abstractmethod - def get_search_args(self, dirname: str) -> typing.List[str]: + def get_search_args(self, dirname: str) -> T.List[str]: pass - def export_dynamic_args(self, env: 'Environment') -> typing.List[str]: + def export_dynamic_args(self, env: 'Environment') -> T.List[str]: return [] - def import_library_args(self, implibname: str) -> typing.List[str]: + def import_library_args(self, implibname: str) -> T.List[str]: """The name of the outputted import library. This implementation is used only on Windows by compilers that use GNU ld """ return [] - def thread_flags(self, env: 'Environment') -> typing.List[str]: + def thread_flags(self, env: 'Environment') -> T.List[str]: return [] - def no_undefined_args(self) -> typing.List[str]: + def no_undefined_args(self) -> T.List[str]: """Arguments to error if there are any undefined symbols at link time. This is the inverse of get_allow_undefined_args(). @@ -380,24 +380,24 @@ class DynamicLinker(metaclass=abc.ABCMeta): """ return [] - def fatal_warnings(self) -> typing.List[str]: + def fatal_warnings(self) -> T.List[str]: """Arguments to make all warnings errors.""" return [] - def bitcode_args(self) -> typing.List[str]: + def bitcode_args(self) -> T.List[str]: raise mesonlib.MesonException('This linker does not support bitcode bundles') - def get_debug_crt_args(self) -> typing.List[str]: + def get_debug_crt_args(self) -> T.List[str]: return [] def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str, rpath_paths: str, build_rpath: str, - install_rpath: str) -> typing.List[str]: + install_rpath: str) -> T.List[str]: return [] def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str, - suffix: str, soversion: str, darwin_versions: typing.Tuple[str, str], - is_shared_module: bool) -> typing.List[str]: + suffix: str, soversion: str, darwin_versions: T.Tuple[str, str], + is_shared_module: bool) -> T.List[str]: return [] @@ -410,13 +410,13 @@ class PosixDynamicLinkerMixin: GNU-like that it makes sense to split this out. """ - def get_output_args(self, outname: str) -> typing.List[str]: + def get_output_args(self, outname: str) -> T.List[str]: return ['-o', outname] - def get_std_shared_lib_args(self) -> typing.List[str]: + def get_std_shared_lib_args(self) -> T.List[str]: return ['-shared'] - def get_search_args(self, dirname: str) -> typing.List[str]: + def get_search_args(self, dirname: str) -> T.List[str]: return ['-L' + dirname] @@ -435,61 +435,61 @@ class GnuLikeDynamicLinkerMixin: 'release': ['-O1'], 'minsize': [], 'custom': [], - } # type: typing.Dict[str, typing.List[str]] + } # type: T.Dict[str, T.List[str]] - def get_buildtype_args(self, buildtype: str) -> typing.List[str]: + def get_buildtype_args(self, buildtype: str) -> T.List[str]: # We can override these in children by just overriding the # _BUILDTYPE_ARGS value. return mesonlib.listify([self._apply_prefix(a) for a in self._BUILDTYPE_ARGS[buildtype]]) - def get_pie_args(self) -> typing.List[str]: + def get_pie_args(self) -> T.List[str]: return ['-pie'] - def get_asneeded_args(self) -> typing.List[str]: + def get_asneeded_args(self) -> T.List[str]: return self._apply_prefix('--as-needed') - def get_link_whole_for(self, args: typing.List[str]) -> typing.List[str]: + def get_link_whole_for(self, args: T.List[str]) -> T.List[str]: if not args: return args return self._apply_prefix('--whole-archive') + args + self._apply_prefix('--no-whole-archive') - def get_allow_undefined_args(self) -> typing.List[str]: + def get_allow_undefined_args(self) -> T.List[str]: return self._apply_prefix('--allow-shlib-undefined') - def get_lto_args(self) -> typing.List[str]: + def get_lto_args(self) -> T.List[str]: return ['-flto'] - def sanitizer_args(self, value: str) -> typing.List[str]: + def sanitizer_args(self, value: str) -> T.List[str]: if value == 'none': return [] return ['-fsanitize=' + value] - def get_coverage_args(self) -> typing.List[str]: + def get_coverage_args(self) -> T.List[str]: return ['--coverage'] - def export_dynamic_args(self, env: 'Environment') -> typing.List[str]: + def export_dynamic_args(self, env: 'Environment') -> T.List[str]: m = env.machines[self.for_machine] if m.is_windows() or m.is_cygwin(): return self._apply_prefix('--export-all-symbols') return self._apply_prefix('-export-dynamic') - def import_library_args(self, implibname: str) -> typing.List[str]: + def import_library_args(self, implibname: str) -> T.List[str]: return self._apply_prefix('--out-implib=' + implibname) - def thread_flags(self, env: 'Environment') -> typing.List[str]: + def thread_flags(self, env: 'Environment') -> T.List[str]: if env.machines[self.for_machine].is_haiku(): return [] return ['-pthread'] - def no_undefined_args(self) -> typing.List[str]: + def no_undefined_args(self) -> T.List[str]: return self._apply_prefix('--no-undefined') - def fatal_warnings(self) -> typing.List[str]: + def fatal_warnings(self) -> T.List[str]: return self._apply_prefix('--fatal-warnings') def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str, - suffix: str, soversion: str, darwin_versions: typing.Tuple[str, str], - is_shared_module: bool) -> typing.List[str]: + suffix: str, soversion: str, darwin_versions: T.Tuple[str, str], + is_shared_module: bool) -> T.List[str]: m = env.machines[self.for_machine] if m.is_windows() or m.is_cygwin(): # For PE/COFF the soname argument has no effect @@ -499,7 +499,7 @@ class GnuLikeDynamicLinkerMixin: def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str, rpath_paths: str, build_rpath: str, - install_rpath: str) -> typing.List[str]: + install_rpath: str) -> T.List[str]: m = env.machines[self.for_machine] if m.is_windows() or m.is_cygwin(): return [] @@ -565,48 +565,48 @@ class AppleDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker): """Apple's ld implementation.""" - def get_asneeded_args(self) -> typing.List[str]: + def get_asneeded_args(self) -> T.List[str]: return self._apply_prefix('-dead_strip_dylibs') - def get_allow_undefined_args(self) -> typing.List[str]: + def get_allow_undefined_args(self) -> T.List[str]: return self._apply_prefix('-undefined,dynamic_lookup') - def get_std_shared_module_args(self, options: 'OptionDictType') -> typing.List[str]: + def get_std_shared_module_args(self, options: 'OptionDictType') -> T.List[str]: return ['-bundle'] + self._apply_prefix('-undefined,dynamic_lookup') - def get_pie_args(self) -> typing.List[str]: + def get_pie_args(self) -> T.List[str]: return ['-pie'] - def get_link_whole_for(self, args: typing.List[str]) -> typing.List[str]: - result = [] # type: typing.List[str] + def get_link_whole_for(self, args: T.List[str]) -> T.List[str]: + result = [] # type: T.List[str] for a in args: result.extend(self._apply_prefix('-force_load')) result.append(a) return result - def get_coverage_args(self) -> typing.List[str]: + def get_coverage_args(self) -> T.List[str]: return ['--coverage'] - def sanitizer_args(self, value: str) -> typing.List[str]: + def sanitizer_args(self, value: str) -> T.List[str]: if value == 'none': return [] return ['-fsanitize=' + value] - def no_undefined_args(self) -> typing.List[str]: + def no_undefined_args(self) -> T.List[str]: return self._apply_prefix('-undefined,error') - def get_always_args(self) -> typing.List[str]: + def get_always_args(self) -> T.List[str]: return self._apply_prefix('-headerpad_max_install_names') + super().get_always_args() - def bitcode_args(self) -> typing.List[str]: + def bitcode_args(self) -> T.List[str]: return self._apply_prefix('-bitcode_bundle') - def fatal_warnings(self) -> typing.List[str]: + def fatal_warnings(self) -> T.List[str]: return self._apply_prefix('-fatal_warnings') def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str, - suffix: str, soversion: str, darwin_versions: typing.Tuple[str, str], - is_shared_module: bool) -> typing.List[str]: + suffix: str, soversion: str, darwin_versions: T.Tuple[str, str], + is_shared_module: bool) -> T.List[str]: if is_shared_module: return [] install_name = ['@rpath/', prefix, shlib_name] @@ -621,7 +621,7 @@ class AppleDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker): def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str, rpath_paths: str, build_rpath: str, - install_rpath: str) -> typing.List[str]: + install_rpath: str) -> T.List[str]: if not rpath_paths and not install_rpath and not build_rpath: return [] # Ensure that there is enough space for install_name_tool in-place @@ -672,21 +672,21 @@ class CcrxDynamicLinker(DynamicLinker): def get_lib_prefix(self) -> str: return '-lib=' - def get_std_shared_lib_args(self) -> typing.List[str]: + def get_std_shared_lib_args(self) -> T.List[str]: return [] - def get_output_args(self, outputname: str) -> typing.List[str]: + def get_output_args(self, outputname: str) -> T.List[str]: return ['-output=%s' % outputname] - def get_search_args(self, dirname: str) -> 'typing.NoReturn': + def get_search_args(self, dirname: str) -> 'T.NoReturn': raise EnvironmentError('rlink.exe does not have a search dir argument') - def get_allow_undefined_args(self) -> typing.List[str]: + def get_allow_undefined_args(self) -> T.List[str]: return [] def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str, - suffix: str, soversion: str, darwin_versions: typing.Tuple[str, str], - is_shared_module: bool) -> typing.List[str]: + suffix: str, soversion: str, darwin_versions: T.Tuple[str, str], + is_shared_module: bool) -> T.List[str]: return [] @@ -702,10 +702,10 @@ class ArmDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker): def get_accepts_rsp(self) -> bool: return False - def get_std_shared_lib_args(self) -> 'typing.NoReturn': + def get_std_shared_lib_args(self) -> 'T.NoReturn': raise mesonlib.MesonException('The Arm Linkers do not support shared libraries') - def get_allow_undefined_args(self) -> typing.List[str]: + def get_allow_undefined_args(self) -> T.List[str]: return [] @@ -717,10 +717,10 @@ class ArmClangDynamicLinker(ArmDynamicLinker): extends a few things as needed. """ - def export_dynamic_args(self, env: 'Environment') -> typing.List[str]: + def export_dynamic_args(self, env: 'Environment') -> T.List[str]: return ['--export_dynamic'] - def import_library_args(self, implibname: str) -> typing.List[str]: + def import_library_args(self, implibname: str) -> T.List[str]: return ['--symdefs=' + implibname] @@ -728,15 +728,15 @@ class PGIDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker): """PGI linker.""" - def get_allow_undefined_args(self) -> typing.List[str]: + def get_allow_undefined_args(self) -> T.List[str]: return [] def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str, - suffix: str, soversion: str, darwin_versions: typing.Tuple[str, str], - is_shared_module: bool) -> typing.List[str]: + suffix: str, soversion: str, darwin_versions: T.Tuple[str, str], + is_shared_module: bool) -> T.List[str]: return [] - def get_std_shared_lib_args(self) -> typing.List[str]: + def get_std_shared_lib_args(self) -> T.List[str]: # PGI -shared is Linux only. if mesonlib.is_windows(): return ['-Bdynamic', '-Mmakedll'] @@ -746,22 +746,22 @@ class PGIDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker): def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str, rpath_paths: str, build_rpath: str, - install_rpath: str) -> typing.List[str]: + install_rpath: str) -> T.List[str]: if not env.machines[self.for_machine].is_windows(): return ['-R' + os.path.join(build_dir, p) for p in rpath_paths] return [] class PGIStaticLinker(StaticLinker): - def __init__(self, exelist: typing.List[str]): + def __init__(self, exelist: T.List[str]): super().__init__(exelist) self.id = 'ar' self.std_args = ['-r'] - def get_std_link_args(self) -> typing.List[str]: + def get_std_link_args(self) -> T.List[str]: return self.std_args - def get_output_args(self, target: str) -> typing.List[str]: + def get_output_args(self, target: str) -> T.List[str]: return [target] class VisualStudioLikeLinkerMixin: @@ -775,7 +775,7 @@ class VisualStudioLikeLinkerMixin: 'release': ['/OPT:REF'], 'minsize': ['/INCREMENTAL:NO', '/OPT:REF'], 'custom': [], - } # type: typing.Dict[str, typing.List[str]] + } # type: T.Dict[str, T.List[str]] def __init__(self, *args, direct: bool = True, machine: str = 'x86', **kwargs): super().__init__(*args, **kwargs) @@ -784,7 +784,7 @@ class VisualStudioLikeLinkerMixin: def invoked_by_compiler(self) -> bool: return not self.direct - def get_debug_crt_args(self) -> typing.List[str]: + def get_debug_crt_args(self) -> T.List[str]: """Arguments needed to select a debug crt for the linker. Sometimes we need to manually select the CRT (C runtime) to use with @@ -794,37 +794,37 @@ class VisualStudioLikeLinkerMixin: """ return self._apply_prefix('/MDd') - def get_output_args(self, outputname: str) -> typing.List[str]: + def get_output_args(self, outputname: str) -> T.List[str]: return self._apply_prefix('/MACHINE:' + self.machine) + self._apply_prefix('/OUT:' + outputname) - def get_always_args(self) -> typing.List[str]: + def get_always_args(self) -> T.List[str]: return self._apply_prefix('/nologo') + super().get_always_args() - def get_search_args(self, dirname: str) -> typing.List[str]: + def get_search_args(self, dirname: str) -> T.List[str]: return self._apply_prefix('/LIBPATH:' + dirname) - def get_std_shared_lib_args(self) -> typing.List[str]: + def get_std_shared_lib_args(self) -> T.List[str]: return self._apply_prefix('/DLL') - def get_debugfile_args(self, targetfile: str) -> typing.List[str]: + def get_debugfile_args(self, targetfile: str) -> T.List[str]: pdbarr = targetfile.split('.')[:-1] pdbarr += ['pdb'] return self._apply_prefix('/DEBUG') + self._apply_prefix('/PDB:' + '.'.join(pdbarr)) - def get_link_whole_for(self, args: typing.List[str]) -> typing.List[str]: + def get_link_whole_for(self, args: T.List[str]) -> T.List[str]: # Only since VS2015 args = mesonlib.listify(args) - l = [] # typing.List[str] + l = [] # T.List[str] for a in args: l.extend(self._apply_prefix('/WHOLEARCHIVE:' + a)) return l - def get_allow_undefined_args(self) -> typing.List[str]: + def get_allow_undefined_args(self) -> T.List[str]: return [] def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str, - suffix: str, soversion: str, darwin_versions: typing.Tuple[str, str], - is_shared_module: bool) -> typing.List[str]: + suffix: str, soversion: str, darwin_versions: T.Tuple[str, str], + is_shared_module: bool) -> T.List[str]: return [] @@ -832,9 +832,9 @@ class MSVCDynamicLinker(VisualStudioLikeLinkerMixin, DynamicLinker): """Microsoft's Link.exe.""" - def __init__(self, for_machine: mesonlib.MachineChoice, always_args: typing.List[str], *, - exelist: typing.Optional[typing.List[str]] = None, - prefix: typing.Union[str, typing.List[str]] = '', + def __init__(self, for_machine: mesonlib.MachineChoice, always_args: T.List[str], *, + exelist: T.Optional[T.List[str]] = None, + prefix: T.Union[str, T.List[str]] = '', machine: str = 'x86', version: str = 'unknown version', direct: bool = True): super().__init__(exelist or ['link.exe'], for_machine, 'link', @@ -845,9 +845,9 @@ class ClangClDynamicLinker(VisualStudioLikeLinkerMixin, DynamicLinker): """Clang's lld-link.exe.""" - def __init__(self, for_machine: mesonlib.MachineChoice, always_args: typing.List[str], *, - exelist: typing.Optional[typing.List[str]] = None, - prefix: typing.Union[str, typing.List[str]] = '', + def __init__(self, for_machine: mesonlib.MachineChoice, always_args: T.List[str], *, + exelist: T.Optional[T.List[str]] = None, + prefix: T.Union[str, T.List[str]] = '', machine: str = 'x86', version: str = 'unknown version', direct: bool = True): super().__init__(exelist or ['lld-link.exe'], for_machine, 'lld-link', @@ -858,7 +858,7 @@ class XilinkDynamicLinker(VisualStudioLikeLinkerMixin, DynamicLinker): """Intel's Xilink.exe.""" - def __init__(self, for_machine: mesonlib.MachineChoice, always_args: typing.List[str], + def __init__(self, for_machine: mesonlib.MachineChoice, always_args: T.List[str], *, version: str = 'unknown version'): super().__init__(['xilink.exe'], for_machine, 'xilink', '', always_args, version=version) @@ -867,23 +867,23 @@ class SolarisDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker): """Sys-V derived linker used on Solaris and OpenSolaris.""" - def get_link_whole_for(self, args: typing.List[str]) -> typing.List[str]: + def get_link_whole_for(self, args: T.List[str]) -> T.List[str]: if not args: return args return self._apply_prefix('--whole-archive') + args + self._apply_prefix('--no-whole-archive') - def no_undefined_args(self) -> typing.List[str]: + def no_undefined_args(self) -> T.List[str]: return ['-z', 'defs'] - def get_allow_undefined_args(self) -> typing.List[str]: + def get_allow_undefined_args(self) -> T.List[str]: return ['-z', 'nodefs'] - def fatal_warnings(self) -> typing.List[str]: + def fatal_warnings(self) -> T.List[str]: return ['-z', 'fatal-warnings'] def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str, rpath_paths: str, build_rpath: str, - install_rpath: str) -> typing.List[str]: + install_rpath: str) -> T.List[str]: if not rpath_paths and not install_rpath and not build_rpath: return [] processed_rpaths = prepare_rpaths(rpath_paths, build_dir, from_dir) @@ -903,8 +903,8 @@ class SolarisDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker): return self._apply_prefix('-rpath,{}'.format(paths)) def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str, - suffix: str, soversion: str, darwin_versions: typing.Tuple[str, str], - is_shared_module: bool) -> typing.List[str]: + suffix: str, soversion: str, darwin_versions: T.Tuple[str, str], + is_shared_module: bool) -> T.List[str]: sostr = '' if soversion is None else '.' + soversion return self._apply_prefix('-soname,{}{}.{}{}'.format(prefix, shlib_name, suffix, sostr)) @@ -919,7 +919,7 @@ class OptlinkDynamicLinker(VisualStudioLikeLinkerMixin, DynamicLinker): # implementations. super().__init__(['optlink.exe'], for_machine, 'optlink', '', [], version=version) - def get_allow_undefined_args(self) -> typing.List[str]: + def get_allow_undefined_args(self) -> T.List[str]: return [] class CudaLinker(PosixDynamicLinkerMixin, DynamicLinker): @@ -956,13 +956,13 @@ class CudaLinker(PosixDynamicLinkerMixin, DynamicLinker): from .compilers import CudaCompiler return CudaCompiler.LINKER_PREFIX - def fatal_warnings(self) -> typing.List[str]: + def fatal_warnings(self) -> T.List[str]: return ['--warning-as-error'] - def get_allow_undefined_args(self) -> typing.List[str]: + def get_allow_undefined_args(self) -> T.List[str]: return [] def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str, - suffix: str, soversion: str, darwin_versions: typing.Tuple[str, str], - is_shared_module: bool) -> typing.List[str]: + suffix: str, soversion: str, darwin_versions: T.Tuple[str, str], + is_shared_module: bool) -> T.List[str]: return [] diff --git a/mesonbuild/mesonlib.py b/mesonbuild/mesonlib.py index 5c3fc45..096f4a9 100644 --- a/mesonbuild/mesonlib.py +++ b/mesonbuild/mesonlib.py @@ -22,13 +22,13 @@ import collections from enum import Enum from functools import lru_cache, update_wrapper from itertools import tee, filterfalse -import typing +import typing as T import uuid from mesonbuild import mlog -_T = typing.TypeVar('_T') -_U = typing.TypeVar('_U') +_T = T.TypeVar('_T') +_U = T.TypeVar('_U') have_fcntl = False have_msvcrt = False @@ -260,7 +260,7 @@ class File: def endswith(self, ending: str) -> bool: return self.fname.endswith(ending) - def split(self, s: str) -> typing.List[str]: + def split(self, s: str) -> T.List[str]: return self.fname.split(s) def __eq__(self, other) -> bool: @@ -331,7 +331,7 @@ class MachineChoice(OrderedEnum): return PerMachine('build.', '')[self] -class PerMachine(typing.Generic[_T]): +class PerMachine(T.Generic[_T]): def __init__(self, build: _T, host: _T): self.build = build self.host = host @@ -345,14 +345,14 @@ class PerMachine(typing.Generic[_T]): def __setitem__(self, machine: MachineChoice, val: _T) -> None: setattr(self, machine.get_lower_case_name(), val) - def miss_defaulting(self) -> "PerMachineDefaultable[typing.Optional[_T]]": + def miss_defaulting(self) -> "PerMachineDefaultable[T.Optional[_T]]": """Unset definition duplicated from their previous to None This is the inverse of ''default_missing''. By removing defaulted machines, we can elaborate the original and then redefault them and thus avoid repeating the elaboration explicitly. """ - unfreeze = PerMachineDefaultable() # type: PerMachineDefaultable[typing.Optional[_T]] + unfreeze = PerMachineDefaultable() # type: PerMachineDefaultable[T.Optional[_T]] unfreeze.build = self.build unfreeze.host = self.host if unfreeze.host == unfreeze.build: @@ -371,14 +371,14 @@ class PerThreeMachine(PerMachine[_T]): super().__init__(build, host) self.target = target - def miss_defaulting(self) -> "PerThreeMachineDefaultable[typing.Optional[_T]]": + def miss_defaulting(self) -> "PerThreeMachineDefaultable[T.Optional[_T]]": """Unset definition duplicated from their previous to None This is the inverse of ''default_missing''. By removing defaulted machines, we can elaborate the original and then redefault them and thus avoid repeating the elaboration explicitly. """ - unfreeze = PerThreeMachineDefaultable() # type: PerThreeMachineDefaultable[typing.Optional[_T]] + unfreeze = PerThreeMachineDefaultable() # type: PerThreeMachineDefaultable[T.Optional[_T]] unfreeze.build = self.build unfreeze.host = self.host unfreeze.target = self.target @@ -391,13 +391,13 @@ class PerThreeMachine(PerMachine[_T]): def matches_build_machine(self, machine: MachineChoice) -> bool: return self.build == self[machine] -class PerMachineDefaultable(PerMachine[typing.Optional[_T]]): +class PerMachineDefaultable(PerMachine[T.Optional[_T]]): """Extends `PerMachine` with the ability to default from `None`s. """ def __init__(self) -> None: super().__init__(None, None) - def default_missing(self) -> "PerMachine[typing.Optional[_T]]": + def default_missing(self) -> "PerMachine[T.Optional[_T]]": """Default host to build This allows just specifying nothing in the native case, and just host in the @@ -409,13 +409,13 @@ class PerMachineDefaultable(PerMachine[typing.Optional[_T]]): return freeze -class PerThreeMachineDefaultable(PerMachineDefaultable, PerThreeMachine[typing.Optional[_T]]): +class PerThreeMachineDefaultable(PerMachineDefaultable, PerThreeMachine[T.Optional[_T]]): """Extends `PerThreeMachine` with the ability to default from `None`s. """ def __init__(self) -> None: PerThreeMachine.__init__(self, None, None, None) - def default_missing(self) -> "PerThreeMachine[typing.Optional[_T]]": + def default_missing(self) -> "PerThreeMachine[T.Optional[_T]]": """Default host to build and target to host. This allows just specifying nothing in the native case, just host in the @@ -467,7 +467,7 @@ def is_netbsd() -> bool: def is_freebsd() -> bool: return platform.system().lower() == 'freebsd' -def exe_exists(arglist: typing.List[str]) -> bool: +def exe_exists(arglist: T.List[str]) -> bool: try: if subprocess.run(arglist, timeout=10).returncode == 0: return True @@ -578,7 +578,7 @@ class Version: # otherwise, the version with a suffix remaining is greater return comparator(len(self._v), len(other._v)) -def _version_extract_cmpop(vstr2: str) -> typing.Tuple[typing.Callable[[typing.Any, typing.Any], bool], str]: +def _version_extract_cmpop(vstr2: str) -> T.Tuple[T.Callable[[T.Any, T.Any], bool], str]: if vstr2.startswith('>='): cmpop = operator.ge vstr2 = vstr2[2:] @@ -686,7 +686,7 @@ def default_libexecdir(): def default_prefix(): return 'c:/' if is_windows() else '/usr/local' -def get_library_dirs() -> typing.List[str]: +def get_library_dirs() -> T.List[str]: if is_windows(): return ['C:/mingw/lib'] # TODO: get programmatically if is_osx(): @@ -770,7 +770,7 @@ if is_windows(): result += (num_backslashes * 2) * '\\' + '"' return result - def split_args(cmd: typing.Sequence[str]) -> typing.List[str]: + def split_args(cmd: T.Sequence[str]) -> T.List[str]: result = [] arg = '' num_backslashes = 0 @@ -976,9 +976,9 @@ def replace_if_different(dst, dst_tmp): else: os.unlink(dst_tmp) -def listify(item: typing.Any, +def listify(item: T.Any, flatten: bool = True, - unholder: bool = False) -> typing.List[typing.Any]: + unholder: bool = False) -> T.List[T.Any]: ''' Returns a list with all args embedded in a list if they are not a list. This function preserves order. @@ -1018,14 +1018,14 @@ def extract_as_list(dict_object, *keys, pop=False, **kwargs): result.append(listify(fetch(key, []), **kwargs)) return result -def typeslistify(item: 'typing.Union[_T, typing.List[_T]]', - types: 'typing.Union[typing.Type[_T], typing.Tuple[typing.Type[_T]]]') -> typing.List[_T]: +def typeslistify(item: 'T.Union[_T, T.List[_T]]', + types: 'T.Union[T.Type[_T], T.Tuple[T.Type[_T]]]') -> T.List[_T]: ''' Ensure that type(@item) is one of @types or a list of items all of which are of type @types ''' if isinstance(item, types): - item = typing.cast(typing.List[_T], [item]) + item = T.cast(T.List[_T], [item]) if not isinstance(item, list): raise MesonException('Item must be a list or one of {!r}'.format(types)) for i in item: @@ -1033,7 +1033,7 @@ def typeslistify(item: 'typing.Union[_T, typing.List[_T]]', raise MesonException('List item must be one of {!r}'.format(types)) return item -def stringlistify(item: typing.Union[str, typing.List[str]]) -> typing.List[str]: +def stringlistify(item: T.Union[str, T.List[str]]) -> T.List[str]: return typeslistify(item, str) def expand_arguments(args): @@ -1060,10 +1060,10 @@ def partition(pred, iterable): t1, t2 = tee(iterable) return filterfalse(pred, t1), filter(pred, t2) -def Popen_safe(args: typing.List[str], write: typing.Optional[str] = None, - stdout: typing.Union[typing.BinaryIO, int] = subprocess.PIPE, - stderr: typing.Union[typing.BinaryIO, int] = subprocess.PIPE, - **kwargs: typing.Any) -> typing.Tuple[subprocess.Popen, str, str]: +def Popen_safe(args: T.List[str], write: T.Optional[str] = None, + stdout: T.Union[T.BinaryIO, int] = subprocess.PIPE, + stderr: T.Union[T.BinaryIO, int] = subprocess.PIPE, + **kwargs: T.Any) -> T.Tuple[subprocess.Popen, str, str]: import locale encoding = locale.getpreferredencoding() if sys.version_info < (3, 6) or not sys.stdout.encoding or encoding.upper() != 'UTF-8': @@ -1073,13 +1073,13 @@ def Popen_safe(args: typing.List[str], write: typing.Optional[str] = None, o, e = p.communicate(write) return p, o, e -def Popen_safe_legacy(args: typing.List[str], write: typing.Optional[str] = None, - stdout: typing.Union[typing.BinaryIO, int] = subprocess.PIPE, - stderr: typing.Union[typing.BinaryIO, int] = subprocess.PIPE, - **kwargs: typing.Any) -> typing.Tuple[subprocess.Popen, str, str]: +def Popen_safe_legacy(args: T.List[str], write: T.Optional[str] = None, + stdout: T.Union[T.BinaryIO, int] = subprocess.PIPE, + stderr: T.Union[T.BinaryIO, int] = subprocess.PIPE, + **kwargs: T.Any) -> T.Tuple[subprocess.Popen, str, str]: p = subprocess.Popen(args, universal_newlines=False, close_fds=False, stdout=stdout, stderr=stderr, **kwargs) - input_ = None # type: typing.Optional[bytes] + input_ = None # type: T.Optional[bytes] if write is not None: input_ = write.encode('utf-8') o, e = p.communicate(input_) @@ -1327,7 +1327,7 @@ def detect_subprojects(spdir_name, current_dir='', result=None): def get_error_location_string(fname: str, lineno: str) -> str: return '{}:{}:'.format(fname, lineno) -def substring_is_in_list(substr: str, strlist: typing.List[str]) -> bool: +def substring_is_in_list(substr: str, strlist: T.List[str]) -> bool: for s in strlist: if substr in s: return True diff --git a/mesonbuild/mintro.py b/mesonbuild/mintro.py index ff9f1d9..ba5901b 100644 --- a/mesonbuild/mintro.py +++ b/mesonbuild/mintro.py @@ -26,7 +26,7 @@ from .ast import IntrospectionInterpreter, build_target_functions, AstConditionL from . import mlog from .backend import backends from .mparser import FunctionNode, ArrayNode, ArgumentNode, StringNode -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import typing as T import os import pathlib @@ -36,22 +36,22 @@ def get_meson_info_file(info_dir: str) -> str: def get_meson_introspection_version() -> str: return '1.0.0' -def get_meson_introspection_required_version() -> List[str]: +def get_meson_introspection_required_version() -> T.List[str]: return ['>=1.0', '<2.0'] class IntroCommand: def __init__(self, desc: str, - func: Optional[Callable[[], Union[dict, list]]] = None, - no_bd: Optional[Callable[[IntrospectionInterpreter], Union[dict, list]]] = None) -> None: + func: T.Optional[T.Callable[[], T.Union[dict, list]]] = None, + no_bd: T.Optional[T.Callable[[IntrospectionInterpreter], T.Union[dict, list]]] = None) -> None: self.desc = desc + '.' self.func = func self.no_bd = no_bd -def get_meson_introspection_types(coredata: Optional[cdata.CoreData] = None, - builddata: Optional[build.Build] = None, - backend: Optional[backends.Backend] = None, - sourcedir: Optional[str] = None) -> Dict[str, IntroCommand]: +def get_meson_introspection_types(coredata: T.Optional[cdata.CoreData] = None, + builddata: T.Optional[build.Build] = None, + backend: T.Optional[backends.Backend] = None, + sourcedir: T.Optional[str] = None) -> T.Dict[str, IntroCommand]: if backend and builddata: benchmarkdata = backend.create_test_serialisation(builddata.get_benchmarks()) testdata = backend.create_test_serialisation(builddata.get_tests()) @@ -60,15 +60,15 @@ def get_meson_introspection_types(coredata: Optional[cdata.CoreData] = None, benchmarkdata = testdata = installdata = None return { - 'benchmarks': IntroCommand('List all benchmarks', func=lambda: list_benchmarks(benchmarkdata)), - 'buildoptions': IntroCommand('List all build options', func=lambda: list_buildoptions(coredata), no_bd=list_buildoptions_from_source), - 'buildsystem_files': IntroCommand('List files that make up the build system', func=lambda: list_buildsystem_files(builddata)), - 'dependencies': IntroCommand('List external dependencies', func=lambda: list_deps(coredata), no_bd=list_deps_from_source), + 'benchmarks': IntroCommand('T.List all benchmarks', func=lambda: list_benchmarks(benchmarkdata)), + 'buildoptions': IntroCommand('T.List all build options', func=lambda: list_buildoptions(coredata), no_bd=list_buildoptions_from_source), + 'buildsystem_files': IntroCommand('T.List files that make up the build system', func=lambda: list_buildsystem_files(builddata)), + 'dependencies': IntroCommand('T.List external dependencies', func=lambda: list_deps(coredata), no_bd=list_deps_from_source), 'scan_dependencies': IntroCommand('Scan for dependencies used in the meson.build file', no_bd=list_deps_from_source), - 'installed': IntroCommand('List all installed files and directories', func=lambda: list_installed(installdata)), + 'installed': IntroCommand('T.List all installed files and directories', func=lambda: list_installed(installdata)), 'projectinfo': IntroCommand('Information about projects', func=lambda: list_projinfo(builddata), no_bd=list_projinfo_from_source), - 'targets': IntroCommand('List top level targets', func=lambda: list_targets(builddata, installdata, backend), no_bd=list_targets_from_source), - 'tests': IntroCommand('List all unit tests', func=lambda: list_tests(testdata)), + 'targets': IntroCommand('T.List top level targets', func=lambda: list_targets(builddata, installdata, backend), no_bd=list_targets_from_source), + 'tests': IntroCommand('T.List all unit tests', func=lambda: list_tests(testdata)), } def add_arguments(parser): @@ -103,12 +103,12 @@ def list_installed(installdata): res[path] = os.path.join(installdata.prefix, installpath) return res -def list_targets_from_source(intr: IntrospectionInterpreter) -> List[Dict[str, Union[bool, str, List[Union[str, Dict[str, Union[str, List[str], bool]]]]]]]: - tlist = [] # type: List[Dict[str, Union[bool, str, List[Union[str, Dict[str, Union[str, List[str], bool]]]]]]] +def list_targets_from_source(intr: IntrospectionInterpreter) -> T.List[T.Dict[str, T.Union[bool, str, T.List[T.Union[str, T.Dict[str, T.Union[str, T.List[str], bool]]]]]]]: + tlist = [] # type: T.List[T.Dict[str, T.Union[bool, str, T.List[T.Union[str, T.Dict[str, T.Union[str, T.List[str], bool]]]]]]] for i in intr.targets: - sources = [] # type: List[str] + sources = [] # type: T.List[str] for n in i['sources']: - args = [] # type: List[Union[str, StringNode]] + args = [] # type: T.List[T.Union[str, StringNode]] if isinstance(n, FunctionNode): args = list(n.args.arguments) if n.func_name in build_target_functions: @@ -143,8 +143,8 @@ def list_targets_from_source(intr: IntrospectionInterpreter) -> List[Dict[str, U return tlist -def list_targets(builddata: build.Build, installdata, backend: backends.Backend) -> List[Dict[str, Union[bool, str, List[Union[str, Dict[str, Union[str, List[str], bool]]]]]]]: - tlist = [] # type: List[Dict[str, Union[bool, str, List[Union[str, Dict[str, Union[str, List[str], bool]]]]]]] +def list_targets(builddata: build.Build, installdata, backend: backends.Backend) -> T.List[T.Dict[str, T.Union[bool, str, T.List[T.Union[str, T.Dict[str, T.Union[str, T.List[str], bool]]]]]]]: + tlist = [] # type: T.List[T.Dict[str, T.Union[bool, str, T.List[T.Union[str, T.Dict[str, T.Union[str, T.List[str], bool]]]]]]] build_dir = builddata.environment.get_build_dir() src_dir = builddata.environment.get_source_dir() @@ -177,11 +177,11 @@ def list_targets(builddata: build.Build, installdata, backend: backends.Backend) tlist.append(t) return tlist -def list_buildoptions_from_source(intr: IntrospectionInterpreter) -> List[Dict[str, Union[str, bool, int, List[str]]]]: +def list_buildoptions_from_source(intr: IntrospectionInterpreter) -> T.List[T.Dict[str, T.Union[str, bool, int, T.List[str]]]]: return list_buildoptions(intr.coredata) -def list_buildoptions(coredata: cdata.CoreData) -> List[Dict[str, Union[str, bool, int, List[str]]]]: - optlist = [] # type: List[Dict[str, Union[str, bool, int, List[str]]]] +def list_buildoptions(coredata: cdata.CoreData) -> T.List[T.Dict[str, T.Union[str, bool, int, T.List[str]]]]: + optlist = [] # type: T.List[T.Dict[str, T.Union[str, bool, int, T.List[str]]]] dir_option_names = ['bindir', 'datadir', @@ -204,7 +204,7 @@ def list_buildoptions(coredata: cdata.CoreData) -> List[Dict[str, Union[str, boo test_options = {k: o for k, o in coredata.builtins.items() if k in test_option_names} core_options = {k: o for k, o in coredata.builtins.items() if k in core_option_names} - def add_keys(options: Dict[str, cdata.UserOption], section: str, machine: str = 'any') -> None: + def add_keys(options: T.Dict[str, cdata.UserOption], section: str, machine: str = 'any') -> None: for key in sorted(options.keys()): opt = options[key] optdict = {'name': key, 'value': opt.value, 'section': section, 'machine': machine} @@ -245,23 +245,23 @@ def list_buildoptions(coredata: cdata.CoreData) -> List[Dict[str, Union[str, boo add_keys(test_options, 'test') return optlist -def find_buildsystem_files_list(src_dir) -> List[str]: +def find_buildsystem_files_list(src_dir) -> T.List[str]: # I feel dirty about this. But only slightly. - filelist = [] # type: List[str] + filelist = [] # type: T.List[str] for root, _, files in os.walk(src_dir): for f in files: if f == 'meson.build' or f == 'meson_options.txt': filelist.append(os.path.relpath(os.path.join(root, f), src_dir)) return filelist -def list_buildsystem_files(builddata: build.Build) -> List[str]: +def list_buildsystem_files(builddata: build.Build) -> T.List[str]: src_dir = builddata.environment.get_source_dir() filelist = find_buildsystem_files_list(src_dir) filelist = [os.path.join(src_dir, x) for x in filelist] return filelist -def list_deps_from_source(intr: IntrospectionInterpreter) -> List[Dict[str, Union[str, bool]]]: - result = [] # type: List[Dict[str, Union[str, bool]]] +def list_deps_from_source(intr: IntrospectionInterpreter) -> T.List[T.Dict[str, T.Union[str, bool]]]: + result = [] # type: T.List[T.Dict[str, T.Union[str, bool]]] for i in intr.dependencies: keys = [ 'name', @@ -273,8 +273,8 @@ def list_deps_from_source(intr: IntrospectionInterpreter) -> List[Dict[str, Unio result += [{k: v for k, v in i.items() if k in keys}] return result -def list_deps(coredata: cdata.CoreData) -> List[Dict[str, Union[str, List[str]]]]: - result = [] # type: List[Dict[str, Union[str, List[str]]]] +def list_deps(coredata: cdata.CoreData) -> T.List[T.Dict[str, T.Union[str, T.List[str]]]]: + result = [] # type: T.List[T.Dict[str, T.Union[str, T.List[str]]]] for d in coredata.deps.host.values(): if d.found(): result += [{'name': d.name, @@ -283,8 +283,8 @@ def list_deps(coredata: cdata.CoreData) -> List[Dict[str, Union[str, List[str]]] 'link_args': d.get_link_args()}] return result -def get_test_list(testdata) -> List[Dict[str, Union[str, int, List[str], Dict[str, str]]]]: - result = [] # type: List[Dict[str, Union[str, int, List[str], Dict[str, str]]]] +def get_test_list(testdata) -> T.List[T.Dict[str, T.Union[str, int, T.List[str], T.Dict[str, str]]]]: + result = [] # type: T.List[T.Dict[str, T.Union[str, int, T.List[str], T.Dict[str, str]]]] for t in testdata: to = {} if isinstance(t.fname, str): @@ -306,13 +306,13 @@ def get_test_list(testdata) -> List[Dict[str, Union[str, int, List[str], Dict[st result.append(to) return result -def list_tests(testdata) -> List[Dict[str, Union[str, int, List[str], Dict[str, str]]]]: +def list_tests(testdata) -> T.List[T.Dict[str, T.Union[str, int, T.List[str], T.Dict[str, str]]]]: return get_test_list(testdata) -def list_benchmarks(benchdata) -> List[Dict[str, Union[str, int, List[str], Dict[str, str]]]]: +def list_benchmarks(benchdata) -> T.List[T.Dict[str, T.Union[str, int, T.List[str], T.Dict[str, str]]]]: return get_test_list(benchdata) -def list_projinfo(builddata: build.Build) -> Dict[str, Union[str, List[Dict[str, str]]]]: +def list_projinfo(builddata: build.Build) -> T.Dict[str, T.Union[str, T.List[T.Dict[str, str]]]]: result = {'version': builddata.project_version, 'descriptive_name': builddata.project_name, 'subproject_dir': builddata.subproject_dir} @@ -325,7 +325,7 @@ def list_projinfo(builddata: build.Build) -> Dict[str, Union[str, List[Dict[str, result['subprojects'] = subprojects return result -def list_projinfo_from_source(intr: IntrospectionInterpreter) -> Dict[str, Union[str, List[Dict[str, str]]]]: +def list_projinfo_from_source(intr: IntrospectionInterpreter) -> T.Dict[str, T.Union[str, T.List[T.Dict[str, str]]]]: sourcedir = intr.source_root files = find_buildsystem_files_list(sourcedir) files = [os.path.normpath(x) for x in files] @@ -339,7 +339,7 @@ def list_projinfo_from_source(intr: IntrospectionInterpreter) -> Dict[str, Union intr.project_data['subproject_dir'] = intr.subproject_dir return intr.project_data -def print_results(options, results: Sequence[Tuple[str, Union[dict, List[Any]]]], indent: int) -> int: +def print_results(options, results: T.Sequence[T.Tuple[str, T.Union[dict, T.List[T.Any]]]], indent: int) -> int: if not results and not options.force_dict: print('No command specified') return 1 @@ -360,7 +360,7 @@ def run(options) -> int: datadir = os.path.join(options.builddir, datadir) infodir = os.path.join(options.builddir, infodir) indent = 4 if options.indent else None - results = [] # type: List[Tuple[str, Union[dict, List[Any]]]] + results = [] # type: T.List[T.Tuple[str, T.Union[dict, T.List[T.Any]]]] sourcedir = '.' if options.builddir == 'meson.build' else options.builddir[:-11] intro_types = get_meson_introspection_types(sourcedir=sourcedir) @@ -413,9 +413,9 @@ def run(options) -> int: return print_results(options, results, indent) -updated_introspection_files = [] # type: List[str] +updated_introspection_files = [] # type: T.List[str] -def write_intro_info(intro_info: Sequence[Tuple[str, Union[dict, List[Any]]]], info_dir: str) -> None: +def write_intro_info(intro_info: T.Sequence[T.Tuple[str, T.Union[dict, T.List[T.Any]]]], info_dir: str) -> None: global updated_introspection_files for i in intro_info: out_file = os.path.join(info_dir, 'intro-{}.json'.format(i[0])) @@ -429,7 +429,7 @@ def write_intro_info(intro_info: Sequence[Tuple[str, Union[dict, List[Any]]]], i def generate_introspection_file(builddata: build.Build, backend: backends.Backend) -> None: coredata = builddata.environment.get_coredata() intro_types = get_meson_introspection_types(coredata=coredata, builddata=builddata, backend=backend) - intro_info = [] # type: List[Tuple[str, Union[dict, List[Any]]]] + intro_info = [] # type: T.List[T.Tuple[str, T.Union[dict, T.List[T.Any]]]] for key, val in intro_types.items(): if not val.func: @@ -445,7 +445,7 @@ def update_build_options(coredata: cdata.CoreData, info_dir) -> None: write_intro_info(intro_info, info_dir) -def split_version_string(version: str) -> Dict[str, Union[str, int]]: +def split_version_string(version: str) -> T.Dict[str, T.Union[str, int]]: vers_list = version.split('.') return { 'full': version, diff --git a/mesonbuild/mlog.py b/mesonbuild/mlog.py index a145cc1..a30d6b9 100644 --- a/mesonbuild/mlog.py +++ b/mesonbuild/mlog.py @@ -17,19 +17,8 @@ import io import sys import time import platform +import typing as T from contextlib import contextmanager -from typing import ( - Any, - Generator, - List, - Optional, - Sequence, - Set, - TextIO, - Tuple, - Union, - cast, -) from pathlib import Path """This is (mostly) a standalone module used to write logging @@ -58,16 +47,16 @@ try: colorize_console = os.isatty(sys.stdout.fileno()) and os.environ.get('TERM') != 'dumb' except Exception: colorize_console = False -log_dir = None # type: Optional[str] -log_file = None # type: Optional[TextIO] +log_dir = None # type: T.Optional[str] +log_file = None # type: T.Optional[T.TextIO] log_fname = 'meson-log.txt' # type: str log_depth = 0 # type: int -log_timestamp_start = None # type: Optional[float] +log_timestamp_start = None # type: T.Optional[float] log_fatal_warnings = False # type: bool log_disable_stdout = False # type: bool log_errors_only = False # type: bool _in_ci = 'CI' in os.environ # type: bool -_logged_once = set() # type: Set[Tuple[str, ...]] +_logged_once = set() # type: T.Set[T.Tuple[str, ...]] def disable() -> None: global log_disable_stdout @@ -95,7 +84,7 @@ def set_timestamp_start(start: float) -> None: global log_timestamp_start log_timestamp_start = start -def shutdown() -> Optional[str]: +def shutdown() -> T.Optional[str]: global log_file if log_file is not None: path = log_file.name @@ -156,8 +145,8 @@ def normal_cyan(text: str) -> AnsiDecorator: # This really should be AnsiDecorator or anything that implements # __str__(), but that requires protocols from typing_extensions -def process_markup(args: Sequence[Union[AnsiDecorator, str]], keep: bool) -> List[str]: - arr = [] # type: List[str] +def process_markup(args: T.Sequence[T.Union[AnsiDecorator, str]], keep: bool) -> T.List[str]: + arr = [] # type: T.List[str] if log_timestamp_start is not None: arr = ['[{:.3f}]'.format(time.monotonic() - log_timestamp_start)] for arg in args: @@ -171,7 +160,7 @@ def process_markup(args: Sequence[Union[AnsiDecorator, str]], keep: bool) -> Lis arr.append(str(arg)) return arr -def force_print(*args: str, **kwargs: Any) -> None: +def force_print(*args: str, **kwargs: T.Any) -> None: if log_disable_stdout: return iostr = io.StringIO() @@ -191,13 +180,13 @@ def force_print(*args: str, **kwargs: Any) -> None: print(cleaned, end='') # We really want a heterogeneous dict for this, but that's in typing_extensions -def debug(*args: Union[str, AnsiDecorator], **kwargs: Any) -> None: +def debug(*args: T.Union[str, AnsiDecorator], **kwargs: T.Any) -> None: arr = process_markup(args, False) if log_file is not None: print(*arr, file=log_file, **kwargs) log_file.flush() -def _debug_log_cmd(cmd: str, args: List[str]) -> None: +def _debug_log_cmd(cmd: str, args: T.List[str]) -> None: if not _in_ci: return args = ['"{}"'.format(x) for x in args] # Quote all args, just in case @@ -206,8 +195,8 @@ def _debug_log_cmd(cmd: str, args: List[str]) -> None: def cmd_ci_include(file: str) -> None: _debug_log_cmd('ci_include', [file]) -def log(*args: Union[str, AnsiDecorator], is_error: bool = False, - **kwargs: Any) -> None: +def log(*args: T.Union[str, AnsiDecorator], is_error: bool = False, + **kwargs: T.Any) -> None: arr = process_markup(args, False) if log_file is not None: print(*arr, file=log_file, **kwargs) @@ -217,8 +206,8 @@ def log(*args: Union[str, AnsiDecorator], is_error: bool = False, if not log_errors_only or is_error: force_print(*arr, **kwargs) -def log_once(*args: Union[str, AnsiDecorator], is_error: bool = False, - **kwargs: Any) -> None: +def log_once(*args: T.Union[str, AnsiDecorator], is_error: bool = False, + **kwargs: T.Any) -> None: """Log variant that only prints a given message one time per meson invocation. This considers nasi decorated values by the values they wrap without @@ -230,16 +219,16 @@ def log_once(*args: Union[str, AnsiDecorator], is_error: bool = False, _logged_once.add(t) log(*args, is_error=is_error, **kwargs) -def _log_error(severity: str, *rargs: Union[str, AnsiDecorator], - once: bool = False, **kwargs: Any) -> None: +def _log_error(severity: str, *rargs: T.Union[str, AnsiDecorator], + once: bool = False, **kwargs: T.Any) -> None: from .mesonlib import get_error_location_string from .environment import build_filename from .mesonlib import MesonException # The tping requirements here are non-obvious. Lists are invariant, - # therefore List[A] and List[Union[A, B]] are not able to be joined + # therefore T.List[A] and T.List[T.Union[A, B]] are not able to be joined if severity == 'warning': - label = [yellow('WARNING:')] # type: List[Union[str, AnsiDecorator]] + label = [yellow('WARNING:')] # type: T.List[T.Union[str, AnsiDecorator]] elif severity == 'error': label = [red('ERROR:')] elif severity == 'deprecation': @@ -253,9 +242,9 @@ def _log_error(severity: str, *rargs: Union[str, AnsiDecorator], if location is not None: location_file = os.path.join(location.subdir, build_filename) location_str = get_error_location_string(location_file, location.lineno) - # Unions are frankly awful, and we have to cast here to get mypy + # Unions are frankly awful, and we have to T.cast here to get mypy # to understand that the list concatenation is safe - location_list = cast(List[Union[str, AnsiDecorator]], [location_str]) + location_list = T.cast(T.List[T.Union[str, AnsiDecorator]], [location_str]) args = location_list + args if once: @@ -266,13 +255,13 @@ def _log_error(severity: str, *rargs: Union[str, AnsiDecorator], if log_fatal_warnings: raise MesonException("Fatal warnings enabled, aborting") -def error(*args: Union[str, AnsiDecorator], once: bool = False, **kwargs: Any) -> None: +def error(*args: T.Union[str, AnsiDecorator], once: bool = False, **kwargs: T.Any) -> None: return _log_error('error', *args, **kwargs, is_error=True, once=once) -def warning(*args: Union[str, AnsiDecorator], once: bool = False, **kwargs: Any) -> None: +def warning(*args: T.Union[str, AnsiDecorator], once: bool = False, **kwargs: T.Any) -> None: return _log_error('warning', *args, **kwargs, is_error=True, once=once) -def deprecation(*args: Union[str, AnsiDecorator], once: bool = False, **kwargs: Any) -> None: +def deprecation(*args: T.Union[str, AnsiDecorator], once: bool = False, **kwargs: T.Any) -> None: return _log_error('deprecation', *args, **kwargs, is_error=True, once=once) def get_relative_path(target: Path, current: Path) -> Path: @@ -290,11 +279,11 @@ def get_relative_path(target: Path, current: Path) -> Path: # we failed, should not get here return target -def exception(e: Exception, prefix: Optional[AnsiDecorator] = None) -> None: +def exception(e: Exception, prefix: T.Optional[AnsiDecorator] = None) -> None: if prefix is None: prefix = red('ERROR:') log() - args = [] # type: List[Union[AnsiDecorator, str]] + args = [] # type: T.List[T.Union[AnsiDecorator, str]] if hasattr(e, 'file') and hasattr(e, 'lineno') and hasattr(e, 'colno'): # Mypy can't figure this out, and it's pretty easy to vidual inspect # that this is correct, so we'll just ignore it. @@ -307,7 +296,7 @@ def exception(e: Exception, prefix: Optional[AnsiDecorator] = None) -> None: # Format a list for logging purposes as a string. It separates # all but the last item with commas, and the last with 'and'. -def format_list(input_list: List[str]) -> str: +def format_list(input_list: T.List[str]) -> str: l = len(input_list) if l > 2: return ' and '.join([', '.join(input_list[:-1]), input_list[-1]]) @@ -319,7 +308,7 @@ def format_list(input_list: List[str]) -> str: return '' @contextmanager -def nested() -> Generator[None, None, None]: +def nested() -> T.Generator[None, None, None]: global log_depth log_depth += 1 try: diff --git a/mesonbuild/modules/fs.py b/mesonbuild/modules/fs.py index 7340fb7..523ad2b 100644 --- a/mesonbuild/modules/fs.py +++ b/mesonbuild/modules/fs.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import typing +import typing as T import hashlib from pathlib import Path, PurePath @@ -22,7 +22,7 @@ from . import ModuleReturnValue from ..mesonlib import MesonException from ..interpreterbase import stringArgs, noKwargs -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from ..interpreter import ModuleState class FSModule(ExtensionModule): @@ -38,7 +38,7 @@ class FSModule(ExtensionModule): """ return Path(state.source_root) / state.subdir / Path(arg).expanduser() - def _check(self, check: str, state: 'ModuleState', args: typing.Sequence[str]) -> ModuleReturnValue: + def _check(self, check: str, state: 'ModuleState', args: T.Sequence[str]) -> ModuleReturnValue: if len(args) != 1: raise MesonException('fs.{} takes exactly one argument.'.format(check)) test_file = self._resolve_dir(state, args[0]) @@ -46,27 +46,27 @@ class FSModule(ExtensionModule): @stringArgs @noKwargs - def exists(self, state: 'ModuleState', args: typing.Sequence[str], kwargs: dict) -> ModuleReturnValue: + def exists(self, state: 'ModuleState', args: T.Sequence[str], kwargs: dict) -> ModuleReturnValue: return self._check('exists', state, args) @stringArgs @noKwargs - def is_symlink(self, state: 'ModuleState', args: typing.Sequence[str], kwargs: dict) -> ModuleReturnValue: + def is_symlink(self, state: 'ModuleState', args: T.Sequence[str], kwargs: dict) -> ModuleReturnValue: return self._check('is_symlink', state, args) @stringArgs @noKwargs - def is_file(self, state: 'ModuleState', args: typing.Sequence[str], kwargs: dict) -> ModuleReturnValue: + def is_file(self, state: 'ModuleState', args: T.Sequence[str], kwargs: dict) -> ModuleReturnValue: return self._check('is_file', state, args) @stringArgs @noKwargs - def is_dir(self, state: 'ModuleState', args: typing.Sequence[str], kwargs: dict) -> ModuleReturnValue: + def is_dir(self, state: 'ModuleState', args: T.Sequence[str], kwargs: dict) -> ModuleReturnValue: return self._check('is_dir', state, args) @stringArgs @noKwargs - def hash(self, state: 'ModuleState', args: typing.Sequence[str], kwargs: dict) -> ModuleReturnValue: + def hash(self, state: 'ModuleState', args: T.Sequence[str], kwargs: dict) -> ModuleReturnValue: if len(args) != 2: raise MesonException('method takes exactly two arguments.') file = self._resolve_dir(state, args[0]) @@ -82,7 +82,7 @@ class FSModule(ExtensionModule): @stringArgs @noKwargs - def size(self, state: 'ModuleState', args: typing.Sequence[str], kwargs: dict) -> ModuleReturnValue: + def size(self, state: 'ModuleState', args: T.Sequence[str], kwargs: dict) -> ModuleReturnValue: if len(args) != 1: raise MesonException('method takes exactly one argument.') file = self._resolve_dir(state, args[0]) @@ -95,7 +95,7 @@ class FSModule(ExtensionModule): @stringArgs @noKwargs - def is_samepath(self, state: 'ModuleState', args: typing.Sequence[str], kwargs: dict) -> ModuleReturnValue: + def is_samepath(self, state: 'ModuleState', args: T.Sequence[str], kwargs: dict) -> ModuleReturnValue: if len(args) != 2: raise MesonException('fs.is_samepath takes exactly two arguments.') file1 = self._resolve_dir(state, args[0]) @@ -111,7 +111,7 @@ class FSModule(ExtensionModule): @stringArgs @noKwargs - def replace_suffix(self, state: 'ModuleState', args: typing.Sequence[str], kwargs: dict) -> ModuleReturnValue: + def replace_suffix(self, state: 'ModuleState', args: T.Sequence[str], kwargs: dict) -> ModuleReturnValue: if len(args) != 2: raise MesonException('method takes exactly two arguments.') original = PurePath(args[0]) @@ -120,7 +120,7 @@ class FSModule(ExtensionModule): @stringArgs @noKwargs - def parent(self, state: 'ModuleState', args: typing.Sequence[str], kwargs: dict) -> ModuleReturnValue: + def parent(self, state: 'ModuleState', args: T.Sequence[str], kwargs: dict) -> ModuleReturnValue: if len(args) != 1: raise MesonException('method takes exactly one argument.') original = PurePath(args[0]) @@ -129,7 +129,7 @@ class FSModule(ExtensionModule): @stringArgs @noKwargs - def name(self, state: 'ModuleState', args: typing.Sequence[str], kwargs: dict) -> ModuleReturnValue: + def name(self, state: 'ModuleState', args: T.Sequence[str], kwargs: dict) -> ModuleReturnValue: if len(args) != 1: raise MesonException('method takes exactly one argument.') original = PurePath(args[0]) diff --git a/mesonbuild/modules/python.py b/mesonbuild/modules/python.py index 07be318..1e2b2ee 100644 --- a/mesonbuild/modules/python.py +++ b/mesonbuild/modules/python.py @@ -15,7 +15,7 @@ import os import json import shutil -import typing +import typing as T from pathlib import Path from .. import mesonlib @@ -495,9 +495,9 @@ class PythonModule(ExtensionModule): def find_installation(self, interpreter, state, args, kwargs): feature_check = FeatureNew('Passing "feature" option to find_installation', '0.48.0') disabled, required, feature = extract_required_kwarg(kwargs, state.subproject, feature_check) - want_modules = mesonlib.extract_as_list(kwargs, 'modules') # type: typing.List[str] - found_modules = [] # type: typing.List[str] - missing_modules = [] # type: typing.List[str] + want_modules = mesonlib.extract_as_list(kwargs, 'modules') # type: T.List[str] + found_modules = [] # type: T.List[str] + missing_modules = [] # type: T.List[str] if len(args) > 1: raise InvalidArguments('find_installation takes zero or one positional argument.') diff --git a/mesonbuild/msetup.py b/mesonbuild/msetup.py index eb3a964..d8b79b2 100644 --- a/mesonbuild/msetup.py +++ b/mesonbuild/msetup.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import typing +import typing as T import time import sys, stat import datetime @@ -101,7 +101,7 @@ class MesonApp: fname = os.path.join(dirname, environment.build_filename) return os.path.exists(fname) - def validate_core_dirs(self, dir1: str, dir2: str) -> typing.Tuple[str, str]: + def validate_core_dirs(self, dir1: str, dir2: str) -> T.Tuple[str, str]: if dir1 is None: if dir2 is None: if not os.path.exists('meson.build') and os.path.exists('../meson.build'): @@ -131,7 +131,7 @@ class MesonApp: return ndir2, ndir1 raise MesonException('Neither directory contains a build file %s.' % environment.build_filename) - def validate_dirs(self, dir1: str, dir2: str, reconfigure: bool, wipe: bool) -> typing.Tuple[str, str]: + def validate_dirs(self, dir1: str, dir2: str, reconfigure: bool, wipe: bool) -> T.Tuple[str, str]: (src_dir, build_dir) = self.validate_core_dirs(dir1, dir2) priv_dir = os.path.join(build_dir, 'meson-private/coredata.dat') if os.path.exists(priv_dir): diff --git a/mesonbuild/mtest.py b/mesonbuild/mtest.py index b0a800f..36caec6 100644 --- a/mesonbuild/mtest.py +++ b/mesonbuild/mtest.py @@ -34,7 +34,7 @@ import subprocess import sys import tempfile import time -import typing +import typing as T from . import build from . import environment @@ -42,7 +42,7 @@ from . import mlog from .dependencies import ExternalProgram from .mesonlib import MesonException, get_wine_shortpath, split_args -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: from .backend.backends import TestSerialisation # GNU autotools interprets a return code of 77 from tests it executes to @@ -148,7 +148,7 @@ def returncode_to_status(retcode: int) -> str: signame = 'SIGinvalid' return '(exit status %d or signal %d %s)' % (retcode, signum, signame) -def env_tuple_to_str(env: typing.Iterable[typing.Tuple[str, str]]) -> str: +def env_tuple_to_str(env: T.Iterable[T.Tuple[str, str]]) -> str: return ''.join(["%s='%s' " % (k, v) for k, v in env]) @@ -187,11 +187,11 @@ class TAPParser: _RE_YAML_START = re.compile(r'(\s+)---.*') _RE_YAML_END = re.compile(r'\s+\.\.\.\s*') - def __init__(self, io: typing.Iterator[str]): + def __init__(self, io: T.Iterator[str]): self.io = io - def parse_test(self, ok: bool, num: int, name: str, directive: typing.Optional[str], explanation: typing.Optional[str]) -> \ - typing.Generator[typing.Union['TAPParser.Test', 'TAPParser.Error'], None, None]: + def parse_test(self, ok: bool, num: int, name: str, directive: T.Optional[str], explanation: T.Optional[str]) -> \ + T.Generator[T.Union['TAPParser.Test', 'TAPParser.Error'], None, None]: name = name.strip() explanation = explanation.strip() if explanation else None if directive is not None: @@ -208,7 +208,7 @@ class TAPParser: yield self.Test(num, name, TestResult.OK if ok else TestResult.FAIL, explanation) - def parse(self) -> typing.Generator[typing.Union['TAPParser.Test', 'TAPParser.Error', 'TAPParser.Version', 'TAPParser.Plan', 'TAPParser.Bailout'], None, None]: + def parse(self) -> T.Generator[T.Union['TAPParser.Test', 'TAPParser.Error', 'TAPParser.Version', 'TAPParser.Plan', 'TAPParser.Bailout'], None, None]: found_late_test = False bailed_out = False plan = None @@ -319,10 +319,10 @@ class TAPParser: class TestRun: @classmethod - def make_exitcode(cls, test: 'TestSerialisation', test_env: typing.Dict[str, str], + def make_exitcode(cls, test: 'TestSerialisation', test_env: T.Dict[str, str], returncode: int, starttime: float, duration: float, - stdo: typing.Optional[str], stde: typing.Optional[str], - cmd: typing.Optional[typing.List[str]]) -> 'TestRun': + stdo: T.Optional[str], stde: T.Optional[str], + cmd: T.Optional[T.List[str]]) -> 'TestRun': if returncode == GNU_SKIP_RETURNCODE: res = TestResult.SKIP elif returncode == GNU_ERROR_RETURNCODE: @@ -334,10 +334,10 @@ class TestRun: return cls(test, test_env, res, returncode, starttime, duration, stdo, stde, cmd) @classmethod - def make_tap(cls, test: 'TestSerialisation', test_env: typing.Dict[str, str], + def make_tap(cls, test: 'TestSerialisation', test_env: T.Dict[str, str], returncode: int, starttime: float, duration: float, stdo: str, stde: str, - cmd: typing.Optional[typing.List[str]]) -> 'TestRun': + cmd: T.Optional[T.List[str]]) -> 'TestRun': res = None num_tests = 0 failed = False @@ -372,10 +372,10 @@ class TestRun: return cls(test, test_env, res, returncode, starttime, duration, stdo, stde, cmd) - def __init__(self, test: 'TestSerialisation', test_env: typing.Dict[str, str], + def __init__(self, test: 'TestSerialisation', test_env: T.Dict[str, str], res: TestResult, returncode: int, starttime: float, duration: float, - stdo: typing.Optional[str], stde: typing.Optional[str], - cmd: typing.Optional[typing.List[str]]): + stdo: T.Optional[str], stde: T.Optional[str], + cmd: T.Optional[T.List[str]]): assert isinstance(res, TestResult) self.res = res self.returncode = returncode @@ -410,7 +410,7 @@ class TestRun: res += '-------\n\n' return res -def decode(stream: typing.Union[None, bytes]) -> str: +def decode(stream: T.Union[None, bytes]) -> str: if stream is None: return '' try: @@ -418,7 +418,7 @@ def decode(stream: typing.Union[None, bytes]) -> str: except UnicodeDecodeError: return stream.decode('iso-8859-1', errors='ignore') -def write_json_log(jsonlogfile: typing.TextIO, test_name: str, result: TestRun) -> None: +def write_json_log(jsonlogfile: T.TextIO, test_name: str, result: TestRun) -> None: jresult = {'name': test_name, 'stdout': result.stdo, 'result': result.res.value, @@ -426,7 +426,7 @@ def write_json_log(jsonlogfile: typing.TextIO, test_name: str, result: TestRun) 'duration': result.duration, 'returncode': result.returncode, 'env': result.env, - 'command': result.cmd} # type: typing.Dict[str, typing.Any] + 'command': result.cmd} # type: T.Dict[str, T.Any] if result.stde: jresult['stderr'] = result.stde jsonlogfile.write(json.dumps(jresult) + '\n') @@ -436,33 +436,33 @@ def run_with_mono(fname: str) -> bool: return True return False -def load_benchmarks(build_dir: str) -> typing.List['TestSerialisation']: +def load_benchmarks(build_dir: str) -> T.List['TestSerialisation']: datafile = Path(build_dir) / 'meson-private' / 'meson_benchmark_setup.dat' if not datafile.is_file(): raise TestException('Directory {!r} does not seem to be a Meson build directory.'.format(build_dir)) with datafile.open('rb') as f: - obj = typing.cast(typing.List['TestSerialisation'], pickle.load(f)) + obj = T.cast(T.List['TestSerialisation'], pickle.load(f)) return obj -def load_tests(build_dir: str) -> typing.List['TestSerialisation']: +def load_tests(build_dir: str) -> T.List['TestSerialisation']: datafile = Path(build_dir) / 'meson-private' / 'meson_test_setup.dat' if not datafile.is_file(): raise TestException('Directory {!r} does not seem to be a Meson build directory.'.format(build_dir)) with datafile.open('rb') as f: - obj = typing.cast(typing.List['TestSerialisation'], pickle.load(f)) + obj = T.cast(T.List['TestSerialisation'], pickle.load(f)) return obj class SingleTestRunner: - def __init__(self, test: 'TestSerialisation', test_env: typing.Dict[str, str], - env: typing.Dict[str, str], options: argparse.Namespace): + def __init__(self, test: 'TestSerialisation', test_env: T.Dict[str, str], + env: T.Dict[str, str], options: argparse.Namespace): self.test = test self.test_env = test_env self.env = env self.options = options - def _get_cmd(self) -> typing.Optional[typing.List[str]]: + def _get_cmd(self) -> T.Optional[T.List[str]]: if self.test.fname[0].endswith('.jar'): return ['java', '-jar'] + self.test.fname elif not self.test.is_cross_built and run_with_mono(self.test.fname[0]): @@ -493,7 +493,7 @@ class SingleTestRunner: self.test.timeout = None return self._run_cmd(wrap + cmd + self.test.cmd_args + self.options.test_args) - def _run_cmd(self, cmd: typing.List[str]) -> TestRun: + def _run_cmd(self, cmd: T.List[str]) -> TestRun: starttime = time.time() if len(self.test.extra_paths) > 0: @@ -629,7 +629,7 @@ class SingleTestRunner: class TestHarness: def __init__(self, options: argparse.Namespace): self.options = options - self.collected_logs = [] # type: typing.List[str] + self.collected_logs = [] # type: T.List[str] self.fail_count = 0 self.expectedfail_count = 0 self.unexpectedpass_count = 0 @@ -638,9 +638,9 @@ class TestHarness: self.timeout_count = 0 self.is_run = False self.tests = None - self.logfilename = None # type: typing.Optional[str] - self.logfile = None # type: typing.Optional[typing.TextIO] - self.jsonlogfile = None # type: typing.Optional[typing.TextIO] + self.logfilename = None # type: T.Optional[str] + self.logfile = None # type: T.Optional[T.TextIO] + self.jsonlogfile = None # type: T.Optional[T.TextIO] if self.options.benchmark: self.tests = load_benchmarks(options.wd) else: @@ -668,7 +668,7 @@ class TestHarness: self.jsonlogfile.close() self.jsonlogfile = None - def merge_suite_options(self, options: argparse.Namespace, test: 'TestSerialisation') -> typing.Dict[str, str]: + def merge_suite_options(self, options: argparse.Namespace, test: 'TestSerialisation') -> T.Dict[str, str]: if ':' in options.setup: if options.setup not in self.build_data.test_setups: sys.exit("Unknown test setup '%s'." % options.setup) @@ -720,7 +720,7 @@ class TestHarness: else: sys.exit('Unknown test result encountered: {}'.format(result.res)) - def print_stats(self, numlen: int, tests: typing.List['TestSerialisation'], + def print_stats(self, numlen: int, tests: T.List['TestSerialisation'], name: str, result: TestRun, i: int) -> None: startpad = ' ' * (numlen - len('%d' % (i + 1))) num = '%s%d/%d' % (startpad, i + 1, len(tests)) @@ -803,16 +803,16 @@ Timeout: %4d return self.total_failure_count() @staticmethod - def split_suite_string(suite: str) -> typing.Tuple[str, str]: + def split_suite_string(suite: str) -> T.Tuple[str, str]: if ':' in suite: # mypy can't figure out that str.split(n, 1) will return a list of # length 2, so we have to help it. - return typing.cast(typing.Tuple[str, str], tuple(suite.split(':', 1))) + return T.cast(T.Tuple[str, str], tuple(suite.split(':', 1))) else: return suite, "" @staticmethod - def test_in_suites(test: 'TestSerialisation', suites: typing.List[str]) -> bool: + def test_in_suites(test: 'TestSerialisation', suites: T.List[str]) -> bool: for suite in suites: (prj_match, st_match) = TestHarness.split_suite_string(suite) for prjst in test.suite: @@ -848,7 +848,7 @@ Timeout: %4d TestHarness.test_in_suites(test, self.options.include_suites)) and not TestHarness.test_in_suites(test, self.options.exclude_suites)) - def get_tests(self) -> typing.List['TestSerialisation']: + def get_tests(self) -> T.List['TestSerialisation']: if not self.tests: print('No tests defined.') return [] @@ -897,8 +897,8 @@ Timeout: %4d self.logfile.write('Inherited environment: {}\n\n'.format(inherit_env)) @staticmethod - def get_wrapper(options: argparse.Namespace) -> typing.List[str]: - wrap = [] # type: typing.List[str] + def get_wrapper(options: argparse.Namespace) -> T.List[str]: + wrap = [] # type: T.List[str] if options.gdb: wrap = [options.gdb_path, '--quiet', '--nh'] if options.repeat > 1: @@ -919,9 +919,9 @@ Timeout: %4d else: return test.name - def run_tests(self, tests: typing.List['TestSerialisation']) -> None: + def run_tests(self, tests: T.List['TestSerialisation']) -> None: executor = None - futures = [] # type: typing.List[typing.Tuple[conc.Future[TestRun], int, typing.List[TestSerialisation], str, int]] + futures = [] # type: T.List[T.Tuple[conc.Future[TestRun], int, T.List[TestSerialisation], str, int]] numlen = len('%d' % len(tests)) self.open_log_files() startdir = os.getcwd() @@ -960,7 +960,7 @@ Timeout: %4d finally: os.chdir(startdir) - def drain_futures(self, futures: typing.List[typing.Tuple['conc.Future[TestRun]', int, typing.List['TestSerialisation'], str, int]]) -> None: + def drain_futures(self, futures: T.List[T.Tuple['conc.Future[TestRun]', int, T.List['TestSerialisation'], str, int]]) -> None: for x in futures: (result, numlen, tests, name, i) = x if self.options.repeat > 1 and self.fail_count: @@ -1052,7 +1052,7 @@ def run(options: argparse.Namespace) -> int: print(e) return 1 -def run_with_args(args: typing.List[str]) -> int: +def run_with_args(args: T.List[str]) -> int: parser = argparse.ArgumentParser(prog='meson test') add_arguments(parser) options = parser.parse_args(args) diff --git a/mesonbuild/optinterpreter.py b/mesonbuild/optinterpreter.py index 8feb4f3..4d790b6 100644 --- a/mesonbuild/optinterpreter.py +++ b/mesonbuild/optinterpreter.py @@ -14,7 +14,7 @@ import os, re import functools -import typing +import typing as T from . import mparser from . import coredata @@ -131,7 +131,7 @@ option_types = {'string': StringParser, 'integer': IntegerParser, 'array': string_array_parser, 'feature': FeatureParser, - } # type: typing.Dict[str, typing.Callable[[str, typing.Dict], coredata.UserOption]] + } # type: T.Dict[str, T.Callable[[str, T.Dict], coredata.UserOption]] class OptionInterpreter: def __init__(self, subproject): diff --git a/mesonbuild/rewriter.py b/mesonbuild/rewriter.py index 5078d3c..b634d00 100644 --- a/mesonbuild/rewriter.py +++ b/mesonbuild/rewriter.py @@ -27,9 +27,9 @@ from .ast import IntrospectionInterpreter, build_target_functions, AstConditionL from mesonbuild.mesonlib import MesonException from . import mlog, environment from functools import wraps -from typing import List, Dict, Optional from .mparser import Token, ArrayNode, ArgumentNode, AssignmentNode, BaseNode, BooleanNode, ElementaryNode, IdNode, FunctionNode, StringNode import json, os, re, sys +import typing as T class RewriterException(MesonException): pass @@ -101,7 +101,7 @@ class RequiredKeys: return wrapped class MTypeBase: - def __init__(self, node: Optional[BaseNode] = None): + def __init__(self, node: T.Optional[BaseNode] = None): if node is None: self.node = self._new_node() # lgtm [py/init-calls-subclass] (node creation does not depend on base class state) else: @@ -142,7 +142,7 @@ class MTypeBase: mlog.warning('Cannot remove a regex in type', mlog.bold(type(self).__name__), '--> skipping') class MTypeStr(MTypeBase): - def __init__(self, node: Optional[BaseNode] = None): + def __init__(self, node: T.Optional[BaseNode] = None): super().__init__(node) def _new_node(self): @@ -155,7 +155,7 @@ class MTypeStr(MTypeBase): self.node.value = str(value) class MTypeBool(MTypeBase): - def __init__(self, node: Optional[BaseNode] = None): + def __init__(self, node: T.Optional[BaseNode] = None): super().__init__(node) def _new_node(self): @@ -168,7 +168,7 @@ class MTypeBool(MTypeBase): self.node.value = bool(value) class MTypeID(MTypeBase): - def __init__(self, node: Optional[BaseNode] = None): + def __init__(self, node: T.Optional[BaseNode] = None): super().__init__(node) def _new_node(self): @@ -181,7 +181,7 @@ class MTypeID(MTypeBase): self.node.value = str(value) class MTypeList(MTypeBase): - def __init__(self, node: Optional[BaseNode] = None): + def __init__(self, node: T.Optional[BaseNode] = None): super().__init__(node) def _new_node(self): @@ -256,7 +256,7 @@ class MTypeList(MTypeBase): self._remove_helper(regex, self._check_regex_matches) class MTypeStrList(MTypeList): - def __init__(self, node: Optional[BaseNode] = None): + def __init__(self, node: T.Optional[BaseNode] = None): super().__init__(node) def _new_element_node(self, value): @@ -276,7 +276,7 @@ class MTypeStrList(MTypeList): return [StringNode] class MTypeIDList(MTypeList): - def __init__(self, node: Optional[BaseNode] = None): + def __init__(self, node: T.Optional[BaseNode] = None): super().__init__(node) def _new_element_node(self, value): @@ -392,7 +392,7 @@ class Rewriter: raise MesonException('Rewriting the meson.build failed') def find_target(self, target: str): - def check_list(name: str) -> List[BaseNode]: + def check_list(name: str) -> T.List[BaseNode]: result = [] for i in self.interpreter.targets: if name == i['name'] or name == i['id']: @@ -744,7 +744,7 @@ class Rewriter: mlog.yellow('{}:{}'.format(os.path.join(to_remove.subdir, environment.build_filename), to_remove.lineno))) elif cmd['operation'] == 'info': - # List all sources in the target + # T.List all sources in the target src_list = [] for i in target['sources']: for j in arg_list_from_node(i): @@ -876,7 +876,7 @@ target_operation_map = { 'info': 'info', } -def list_to_dict(in_list: List[str]) -> Dict[str, str]: +def list_to_dict(in_list: T.List[str]) -> T.Dict[str, str]: result = {} it = iter(in_list) try: @@ -889,7 +889,7 @@ def list_to_dict(in_list: List[str]) -> Dict[str, str]: raise TypeError('in_list parameter of list_to_dict must have an even length.') return result -def generate_target(options) -> List[dict]: +def generate_target(options) -> T.List[dict]: return [{ 'type': 'target', 'target': options.target, @@ -899,7 +899,7 @@ def generate_target(options) -> List[dict]: 'target_type': options.tgt_type, }] -def generate_kwargs(options) -> List[dict]: +def generate_kwargs(options) -> T.List[dict]: return [{ 'type': 'kwargs', 'function': options.function, @@ -908,14 +908,14 @@ def generate_kwargs(options) -> List[dict]: 'kwargs': list_to_dict(options.kwargs), }] -def generate_def_opts(options) -> List[dict]: +def generate_def_opts(options) -> T.List[dict]: return [{ 'type': 'default_options', 'operation': options.operation, 'options': list_to_dict(options.options), }] -def genreate_cmd(options) -> List[dict]: +def genreate_cmd(options) -> T.List[dict]: if os.path.exists(options.json): with open(options.json, 'r') as fp: return json.load(fp) diff --git a/mesonbuild/wrap/wrap.py b/mesonbuild/wrap/wrap.py index 3ea1f1e..abbeb9e 100644 --- a/mesonbuild/wrap/wrap.py +++ b/mesonbuild/wrap/wrap.py @@ -25,12 +25,12 @@ import stat import subprocess import sys import configparser -import typing +import typing as T from . import WrapMode from ..mesonlib import ProgressBar, MesonException -if typing.TYPE_CHECKING: +if T.TYPE_CHECKING: import http.client try: @@ -48,7 +48,7 @@ ssl_warning_printed = False whitelist_subdomain = 'wrapdb.mesonbuild.com' -def quiet_git(cmd: typing.List[str], workingdir: str) -> typing.Tuple[bool, str]: +def quiet_git(cmd: T.List[str], workingdir: str) -> T.Tuple[bool, str]: git = shutil.which('git') if not git: return False, 'Git program not found.' @@ -258,7 +258,7 @@ class Resolver: raise WrapException('Git program not found.') revno = self.wrap.get('revision') is_shallow = False - depth_option = [] # type: typing.List[str] + depth_option = [] # type: T.List[str] if self.wrap.values.get('depth', '') != '': is_shallow = True depth_option = ['--depth', self.wrap.values.get('depth')] @@ -330,7 +330,7 @@ class Resolver: subprocess.check_call([svn, 'checkout', '-r', revno, self.wrap.get('url'), self.directory], cwd=self.subdir_root) - def get_data(self, urlstring: str) -> typing.Tuple[str, str]: + def get_data(self, urlstring: str) -> T.Tuple[str, str]: blocksize = 10 * 1024 h = hashlib.sha256() tmpfile = tempfile.NamedTemporaryFile(mode='wb', dir=self.cachedir, delete=False) -- cgit v1.1