diff --git a/docs/markdown/Features-module.md b/docs/markdown/Features-module.md new file mode 100644 index 000000000000..2d921fbd3a84 --- /dev/null +++ b/docs/markdown/Features-module.md @@ -0,0 +1,320 @@ +# Features module + +## Overview + +Dealing with a numerous of CPU features within C and C++ compilers poses intricate challenges, +particularly when endeavoring to support an extensive set of CPU features across diverse +architectures and multiple compilers. Furthermore, the conundrum of accommodating +both fundamental features and supplementary features dispatched at runtime +further complicates matters. + +In addition, the task of streamlining generic interface implementations often leads to the necessity +of intricate solutions, which can obscure code readability and hinder debugging and maintenance. +Nested namespaces, recursive sources, complex precompiled macros, or intricate meta templates +are commonly employed but can result in convoluted code structures. + +Enter the proposed module, which offers a simple pragmatic multi-target solution to +facilitate the management of CPU features with heightened ease and reliability. + +In essence, this module introduces the following core principle: + +```C +// Include header files for enabled CPU features +#ifdef HAVE_SSE + #include +#endif +#ifdef HAVE_SSE2 + #include +#endif +#ifdef HAVE_SSE3 + #include +#endif +#ifdef HAVE_SSSE3 + #include +#endif +#ifdef HAVE_SSE41 + #include +#endif +#ifdef HAVE_NEON + #include +#endif +// ... (similar blocks for other features) + +// MTARGETS_CURRENT defined as compiler argument via `features.multi_targets()` +#ifdef MTARGETS_CURRENT + #define TARGET_SFX(X) X##_##MTARGETS_CURRENT +#else + // baseline or when building source without this module. + #define TARGET_SFX(X) X +#endif + +// Core function utilizing feature-specific implementations +void TARGET_SFX(my_kernal)(const float *src, float *dst) +{ +// Feature-based branching +#if defined(HAVE_SSE41) + // Definitions for implied features always present, + // regardless of the compiler used. + #ifndef HAVE_SSSE3 + #error "Alawys defined" + #endif +#elif defined(HAVE_SSE2) + #ifndef HAVE_SSE2 + #error "Alawys defined" + #endif +#elif defined(HAVE_ASIMDHP) + #if !defined(HAVE_NEON) || !defined(HAVE_ASIMD) + #error "Alawys defined" + #endif +#elif defined(HAVE_ASIMD) + #ifndef HAVE_NEON_VFPV4 + #error "Alawys defined" + #endif +#elif defined(HAVE_NEON_F16) + #ifndef HAVE_NEON + #error "Alawys defined" + #endif +#else + // fallback to C scalar +#endif +} +``` + +Key Takeaways from the Code: + +- The code employs feature-centric definitions, enhancing readability + and flexibility while sidestepping the need for feature grouping. + +- Notably, compiler-built definitions are circumvented, thereby affording + seamless management of enabled/disabled features and accommodating diverse compilers and feature sets. + Notably, this accommodates compilers like MSVC, which might lack definitions for specific CPU features. + +- The code remains agnostic about its build process, granting it remarkable versatility + in managing generated objects. This empowers the ability to elevate baseline features at will, + adjust additional dispatched features, and effect changes without necessitating code modifications. + +- The architecture permits the construction of a singular source, which can be compiled multiple times. + This strategic approach simplifies the implementation of generic interfaces, streamlining the development process. + + +## Usage +To use this module, just do: **`features = import('features')`**. The +following functions will then be available as methods on the object +with the name `features`. You can, of course, replace the name `features` +with anything else. + +### features.new() + +**Signature** +```meson +FeatureObject features.new( + # Positional arguments: + str, + int, + # Keyword arguments: + implies : FeatureOject | list[FeatureObject] = [], + group : str | list[str] = [], + args : str | dict[str] | list[str | dict[str]] = [], + detect : str | dict[str] | list[str | dict[str]] = [], + test_code : str | File = '', + extra_tests : dict[str | file] = {}, + disable : str = '' +) +``` + +The `features.new()` function plays a pivotal role within the Features Module. +It creates a fresh mutable instance of FeatureObject, an essential component +for facilitating the functionality of other methods within the module. + +This function requires two positional arguments. The first argument pertains to the feature's name, +while the second one involves the interest level of the feature. This interest level governs sorting +operations and aids in resolving conflicts among arguments with differing priorities. + +Additional keyword arguments are elaborated as follows: + +* `implies` **FeatureOject | list[FeatureObject]**: + An optional single feature object or an array of feature objects + representing predecessor features. It is noteworthy that two features can imply each other. + Such mutual implication can prove beneficial in addressing compatibility concerns with compilers or hardware. + For instance, while some compilers might require enabling both `AVX2` and `FMA3` simultaneously, + others may permit independent activation. + +* `group` **str | list[str]**: + An optional single feature name or an array of additional feature names. These names are appended as + supplementary definitions that can be passed to the source. + +* `args` **str | dict[str] | list[str | dict[str]] = []**: + An optional single compiler argument or an array of compiler arguments that must be enabled for + the corresponding feature. Each argument can be a string or a dictionary containing four elements. + These elements handle conflicts arising from arguments of implied features or when concatenating two features: + - `val` **str**: + The compiler argument. + - `match` **str | empty**: + A regular expression to match arguments of implied features that necessitate filtering or removal. + - `mfilter` **str | empty**: + A regular expression to identify specific strings from matched arguments. + These strings are combined with `val`. If `mfilter` is empty or undefined, + matched arguments from `match` will not be combined with `val`. + - `mjoin` **str | empty**: + A separator used to join all filtered arguments. + If undefined or empty, filtered arguments are joined without a separator. + +* `detect` **str | dict[str] | list[str | dict[str]] = [] = []**: + An optional single feature name or an array of feature names to be detected at runtime. + If no feature names are specified, the values from the `group` will be used. + If the `group` doesn't provide values, the feature's name is employed instead. + Similar to args, each feature name can be a string or a dictionary with four + elements to manage conflicts of implied feature names. + Refer to `features.multi_targets()` or `features.test()` for further clarity. + +* `test_code` **str | File = ''**: + An optional block of C/C++ code or the path to a source file for testing against the compiler. + Successful compilation indicates feature support. + +* `extra_tests` **dict[str | file] = {}**: + An optional dictionary containing extra tests. The keys represent test names, + and the associated values are C/C++ code or paths to source files. + Successful tests lead to compiler definitions based on the test names. + +* `disable` **str = ''**: + An optional string to mark a feature as disabled. + If the string is empty or undefined, the feature is considered not disabled. + +The function returns a new instance of `FeatureObject`. + +Example: + +```Meson +cpu = host_machine.cpu_family() +features = import('features') + +ASIMD = features.new( + 'ASIMD', 1, group: ['NEON', 'NEON_VFPV4', 'NEON_VFPV4'], + args: cpu == 'aarch64' ? '' : [ + '-mfpu=neon-fp-armv8', + '-march=armv8-a+simd' + ], + disable: cpu in ['arm', 'aarch64'] ? '' : 'Not supported by ' + cpu +) +# ARMv8.2 half-precision & vector arithm +ASIMDHP = features.new( + 'ASIMDHP', 2, implies: ASIMD, + args: { + 'val': '-march=armv8.2-a+fp16', + # search for any argument starts with `-match=` + 'match': '-march=', + # gets any string starts with `+` and apended to the value of `val` + 'mfilter': '\+.*' + } +) +## ARMv8.2 dot product +ASIMDDP = features.new( + 'ASIMDDP', 3, implies: ASIMD, + args: {'val': '-march=armv8.2-a+dotprod', 'match': '-march=.*', 'mfilter': '\+.*'} +) +## ARMv8.2 Single & half-precision Multiply +ASIMDFHM = features.new( + 'ASIMDFHM', 4, implies: ASIMDHP, + args: {'val': '-march=armv8.2-a+fp16fml', 'match': '-march=.*', 'mfilter': '\+.*'} +) +``` +### features.test() +**Signature** +```meson +[bool, Dict] features.test( + # Positional arguments: + FeatureObject... + # Keyword arguments: + anyfet : bool = false, + force_args : str | list[str] | empty = empty, + compiler : Compiler | empty = empty, + cached : bool = true +) +``` + +Test one or a list of features against the compiler and retrieve a dictionary containing +essential information required for compiling a source that depends on these features. + +A feature is deemed supported if it fulfills the following criteria: + + - It is not marked as disabled. + - The compiler accommodates the features arguments. + - Successful compilation of the designated test file or code. + - The implied features are supported by the compiler, aligning with + the criteria mentioned above. + +This function requires at least one feature object as positional argument, +and additional keyword arguments are elaborated as follows: + +- `anyfet` **bool = false**: + If set to true, the returned dictionary will encompass information regarding + the maximum features available that are supported by the compiler. + This extends beyond the specified features and includes their implied features. +- `force_args` **str | list[str] | empty = empty**: + An optional single compiler argument or an array of compiler arguments to be + employed instead of the designated features' arguments when testing the + test code against the compiler. This can be useful for detecting host features. +- `compiler` **Compiler | empty = empty**: + A Compiler object to be tested against. If not defined, + the function will default to the standard C or C++ compiler. +- `cached`: **bool = true**: + Enable or disable the cache. By default, the cache is enabled, + enhancing efficiency by storing previous results. + +This function returns a list of two items. The first item is a boolean value, +set to true if the compiler supports the feature and false if it does not. +The second item is a dictionary that encapsulates the test results, outlined as follows: + +**structure** +```meson +{ + 'target_name' : str, + 'prevalent_features' : list[str], + 'features' : list[str], + 'args' : list[str], + 'detect' : list[str], + 'defines' : list[str], + 'undefines' : list[str], + 'is_supported' : bool, + 'is_disabled' : bool, + 'fail_reason' : str +} +``` + +### features.multi_targets() +**Signature** +```meson +TargetsObject features.multi_targets( + # Positional arguments: + str, + ( + str | File | CustomTarget | CustomTargetIndex | + GeneratedList | StructuredSources | ExtractedObjects | + BuildTarget + )..., + # Keyword arguments: + dispatch : FeatureObject | list[FeatureObject] = [], + baseline : empty | list[FeatureObject] = empty, + prefix : str = '', + keep_sort : bool = false, + compiler : empty | compiler = empty, + cached : bool = True, + **known_stlib_kwargs +) +``` + +### features.sort() +**Signature** +```meson +``` + +### features.implicit() +**Signature** +```meson +``` + +### features.implicit_c() +**Signature** +```meson +``` + diff --git a/docs/sitemap.txt b/docs/sitemap.txt index 21f495e1d1da..a82c3671ddf0 100644 --- a/docs/sitemap.txt +++ b/docs/sitemap.txt @@ -59,6 +59,7 @@ index.md Windows-module.md i18n-module.md Wayland-module.md + Features-module.md Java.md Vala.md D.md diff --git a/mesonbuild/compilers/__init__.py b/mesonbuild/compilers/__init__.py index 116b3fa7a43e..3aa64673ad64 100644 --- a/mesonbuild/compilers/__init__.py +++ b/mesonbuild/compilers/__init__.py @@ -4,6 +4,7 @@ # Public symbols for compilers sub-package when using 'from . import compilers' __all__ = [ 'Compiler', + 'CompileResult', 'RunResult', 'all_languages', @@ -45,6 +46,7 @@ # Bring symbols from each module into compilers sub-package namespace from .compilers import ( Compiler, + CompileResult, RunResult, all_languages, clib_langs, diff --git a/mesonbuild/interpreter/interpreter.py b/mesonbuild/interpreter/interpreter.py index 3c542cc4e538..ef51a9c3fd67 100644 --- a/mesonbuild/interpreter/interpreter.py +++ b/mesonbuild/interpreter/interpreter.py @@ -1121,7 +1121,7 @@ def set_backend(self) -> None: return from ..backend import backends - if OptionKey('genvslite') in self.user_defined_options.cmd_line_options: + if self.user_defined_options and OptionKey('genvslite') in self.user_defined_options.cmd_line_options: # Use of the '--genvslite vsxxxx' option ultimately overrides any '--backend xxx' # option the user may specify. backend_name = self.coredata.optstore.get_value_for(OptionKey('genvslite')) diff --git a/mesonbuild/modules/features/__init__.py b/mesonbuild/modules/features/__init__.py new file mode 100644 index 000000000000..cd71ca43e738 --- /dev/null +++ b/mesonbuild/modules/features/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) 2023, NumPy Developers. + +from typing import TYPE_CHECKING + +from .module import Module + +if TYPE_CHECKING: + from ...interpreter import Interpreter + +def initialize(interpreter: 'Interpreter') -> Module: + return Module() diff --git a/mesonbuild/modules/features/feature.py b/mesonbuild/modules/features/feature.py new file mode 100644 index 000000000000..7e0f621e543f --- /dev/null +++ b/mesonbuild/modules/features/feature.py @@ -0,0 +1,356 @@ +# Copyright (c) 2023, NumPy Developers. +# All rights reserved. +import re +from typing import ( + Dict, Set, Tuple, List, Callable, Optional, + Union, Any, Iterable, cast, TYPE_CHECKING +) +from dataclasses import dataclass, field +from ...mesonlib import File, MesonException +from ...interpreter.type_checking import NoneType +from ...interpreterbase.decorators import ( + noKwargs, noPosargs, KwargInfo, typed_kwargs, typed_pos_args, + ContainerTypeInfo +) +from .. import ModuleObject + +if TYPE_CHECKING: + from typing import TypedDict + from typing_extensions import NotRequired + from ...interpreterbase import TYPE_var, TYPE_kwargs + from ...compilers import Compiler + from .. import ModuleState + +@dataclass(unsafe_hash=True, order=True) +class ConflictAttr: + """ + Data class representing an feature attribute that may conflict + with other features attributes. + + The reason behind this class to clear any possible conflicts with + compiler arguments when they joined together due gathering + the implied features or concatenate non-implied features. + + Attributes: + val: The value of the feature attribute. + match: Regular expression pattern for matching conflicted values + (optional). + mfilter: Regular expression pattern for filtering these conflicted values + (optional). + mjoin: String used to join filtered values (optional) + + """ + val: str = field(hash=True, compare=True) + match: Union[re.Pattern, None] = field( + default=None, hash=False, compare=False + ) + mfilter: Union[re.Pattern, None] = field( + default=None, hash=False, compare=False + ) + mjoin: str = field(default='', hash=False, compare=False) + + def copy(self) -> 'ConflictAttr': + return ConflictAttr(**self.__dict__) + + def to_dict(self) -> Dict[str, str]: + ret: Dict[str, str] = {} + for attr in ('val', 'mjoin'): + ret[attr] = getattr(self, attr) + for attr in ('match', 'mfilter'): + val = getattr(self, attr) + if not val: + val = '' + else: + val = str(val) + ret[attr] = val + return ret + +class KwargConfilctAttr(KwargInfo): + def __init__(self, func_name: str, opt_name: str, default: Any = None): + types = ( + NoneType, str, ContainerTypeInfo(dict, str), + ContainerTypeInfo(list, (dict, str)) + ) + super().__init__( + opt_name, types, + convertor = lambda values: self.convert( + func_name, opt_name, values + ), + default = default + ) + + @staticmethod + def convert(func_name:str, opt_name: str, values: 'IMPLIED_ATTR', + ) -> Union[None, List[ConflictAttr]]: + if values is None: + return None + ret: List[ConflictAttr] = [] + values = [values] if isinstance(values, (str, dict)) else values + accepted_keys = ('val', 'match', 'mfilter', 'mjoin') + for edict in values: + if isinstance(edict, str): + if edict: + ret.append(ConflictAttr(val=edict)) + continue + if not isinstance(edict, dict): + # It shouldn't happen + # TODO: need exception here + continue + unknown_keys = [k for k in edict.keys() if k not in accepted_keys] + if unknown_keys: + raise MesonException( + f'{func_name}: unknown keys {unknown_keys} in ' + f'option {opt_name}' + ) + val = edict.get('val') + if val is None: + raise MesonException( + f'{func_name}: option "{opt_name}" requires ' + f'a dictionary with key "val" to be set' + ) + implattr = ConflictAttr(val=val, mjoin=edict.get('mjoin', '')) + for cattr in ('match', 'mfilter'): + cval = edict.get(cattr) + if not cval: + continue + try: + ccval = re.compile(cval) + except Exception as e: + raise MesonException( + '{func_name}: unable to ' + f'compile the regex in option "{opt_name}"\n' + f'"{cattr}:{cval}" -> {str(e)}' + ) + setattr(implattr, cattr, ccval) + ret.append(implattr) + return ret + +if TYPE_CHECKING: + IMPLIED_ATTR = Union[ + None, str, Dict[str, str], List[ + Union[str, Dict[str, str]] + ] + ] + class FeatureKwArgs(TypedDict): + #implies: Optional[List['FeatureObject']] + implies: NotRequired[List[Any]] + group: NotRequired[List[str]] + detect: NotRequired[List[ConflictAttr]] + args: NotRequired[List[ConflictAttr]] + test_code: NotRequired[Union[str, File]] + extra_tests: NotRequired[Dict[str, Union[str, File]]] + disable: NotRequired[str] + + class FeatureUpdateKwArgs(FeatureKwArgs): + name: NotRequired[str] + interest: NotRequired[int] + +class FeatureObject(ModuleObject): + name: str + interest: int + implies: Set['FeatureObject'] + group: List[str] + detect: List[ConflictAttr] + args: List[ConflictAttr] + test_code: Union[str, File] + extra_tests: Dict[str, Union[str, File]] + disable: str + + def __init__(self, state: 'ModuleState', + args: List['TYPE_var'], + kwargs: 'TYPE_kwargs') -> None: + + super().__init__() + + @typed_pos_args('features.new', str, int) + @typed_kwargs('features.new', + KwargInfo( + 'implies', + (FeatureObject, ContainerTypeInfo(list, FeatureObject)), + default=[], listify=True + ), + KwargInfo( + 'group', (str, ContainerTypeInfo(list, str)), + default=[], listify=True + ), + KwargConfilctAttr('features.new', 'detect', default=[]), + KwargConfilctAttr('features.new', 'args', default=[]), + KwargInfo('test_code', (str, File), default=''), + KwargInfo( + 'extra_tests', (ContainerTypeInfo(dict, (str, File))), + default={} + ), + KwargInfo('disable', (str), default=''), + ) + def init_attrs(state: 'ModuleState', + args: Tuple[str, int], + kwargs: 'FeatureKwArgs') -> None: + self.name = args[0] + self.interest = args[1] + self.implies = set(kwargs['implies']) + self.group = kwargs['group'] + self.detect = kwargs['detect'] + self.args = kwargs['args'] + self.test_code = kwargs['test_code'] + self.extra_tests = kwargs['extra_tests'] + self.disable: str = kwargs['disable'] + if not self.detect: + if self.group: + self.detect = [ConflictAttr(val=f) for f in self.group] + else: + self.detect = [ConflictAttr(val=self.name)] + + init_attrs(state, args, kwargs) + self.methods.update({ + 'update': self.update_method, + 'get': self.get_method, + }) + + def update_method(self, state: 'ModuleState', args: List['TYPE_var'], + kwargs: 'TYPE_kwargs') -> 'FeatureObject': + @noPosargs + @typed_kwargs('features.FeatureObject.update', + KwargInfo('name', (NoneType, str)), + KwargInfo('interest', (NoneType, int)), + KwargInfo( + 'implies', ( + NoneType, FeatureObject, + ContainerTypeInfo(list, FeatureObject) + ), + listify=True + ), + KwargInfo( + 'group', (NoneType, str, ContainerTypeInfo(list, str)), + listify=True + ), + KwargConfilctAttr('features.FeatureObject.update', 'detect'), + KwargConfilctAttr('features.FeatureObject.update', 'args'), + KwargInfo('test_code', (NoneType, str, File)), + KwargInfo( + 'extra_tests', ( + NoneType, ContainerTypeInfo(dict, (str, File))) + ), + KwargInfo('disable', (NoneType, str)), + ) + def update(state: 'ModuleState', args: List['TYPE_var'], + kwargs: 'FeatureUpdateKwArgs') -> None: + for k, v in kwargs.items(): + if v is not None and k != 'implies': + setattr(self, k, v) + implies = kwargs.get('implies') + if implies is not None: + self.implies = set(implies) + update(state, args, kwargs) + return self + + @noKwargs + @typed_pos_args('features.FeatureObject.get', str) + def get_method(self, state: 'ModuleState', args: Tuple[str], + kwargs: 'TYPE_kwargs') -> 'TYPE_var': + + impl_lst = lambda lst: [v.to_dict() for v in lst] + noconv = lambda v: v + dfunc = { + 'name': noconv, + 'interest': noconv, + 'group': noconv, + 'implies': lambda v: [fet.name for fet in sorted(v)], + 'detect': impl_lst, + 'args': impl_lst, + 'test_code': noconv, + 'extra_tests': noconv, + 'disable': noconv + } + cfunc: Optional[Callable[[str], 'TYPE_var']] = dfunc.get(args[0]) + if cfunc is None: + raise MesonException(f'Key {args[0]!r} is not in the feature.') + val = getattr(self, args[0]) + return cfunc(val) + + def get_implicit(self, _caller: Set['FeatureObject'] = None + ) -> Set['FeatureObject']: + # infinity recursive guard since + # features can imply each other + _caller = {self, } if not _caller else _caller.union({self, }) + implies = self.implies.difference(_caller) + ret = self.implies + for sub_fet in implies: + ret = ret.union(sub_fet.get_implicit(_caller)) + return ret + + @staticmethod + def get_implicit_multi(features: Iterable['FeatureObject']) -> Set['FeatureObject']: + implies = set().union(*[f.get_implicit() for f in features]) + return implies + + @staticmethod + def get_implicit_combine_multi(features: Iterable['FeatureObject']) -> Set['FeatureObject']: + return FeatureObject.get_implicit_multi(features).union(features) + + @staticmethod + def sorted_multi(features: Iterable[Union['FeatureObject', Iterable['FeatureObject']]], + reverse: bool = False + ) -> List[Union['FeatureObject', Iterable['FeatureObject']]]: + def sort_cb(k: Union[FeatureObject, Iterable[FeatureObject]]) -> int: + if isinstance(k, FeatureObject): + return k.interest + # keep prevalent features and erase any implied features + implied_features = FeatureObject.get_implicit_multi(k) + prevalent_features = set(k).difference(implied_features) + if len(prevalent_features) == 0: + # It happens when all features imply each other. + # Set the highest interested feature + return sorted(k)[-1].interest + # multiple features + rank = max(f.interest for f in prevalent_features) + # FIXME: that's not a safe way to increase the rank for + # multi features this why this function isn't considerd + # accurate. + rank += len(prevalent_features) -1 + return rank + return sorted(features, reverse=reverse, key=sort_cb) + + @staticmethod + def features_names(features: Iterable[Union['FeatureObject', Iterable['FeatureObject']]] + ) -> List[Union[str, List[str]]]: + return [ + fet.name if isinstance(fet, FeatureObject) + else [f.name for f in fet] + for fet in features + ] + + def __repr__(self) -> str: + args = ', '.join([ + f'{attr} = {str(getattr(self, attr))}' + for attr in [ + 'group', 'implies', + 'detect', 'args', + 'test_code', 'extra_tests', + 'disable' + ] + ]) + return f'FeatureObject({self.name}, {self.interest}, {args})' + + def __hash__(self) -> int: + return hash(self.name) + + def __eq__(self, robj: object) -> bool: + if not isinstance(robj, FeatureObject): + return False + return self is robj and self.name == robj.name + + def __lt__(self, robj: object) -> Any: + if not isinstance(robj, FeatureObject): + return NotImplemented + return self.interest < robj.interest + + def __le__(self, robj: object) -> Any: + if not isinstance(robj, FeatureObject): + return NotImplemented + return self.interest <= robj.interest + + def __gt__(self, robj: object) -> Any: + return robj < self + + def __ge__(self, robj: object) -> Any: + return robj <= self diff --git a/mesonbuild/modules/features/module.py b/mesonbuild/modules/features/module.py new file mode 100644 index 000000000000..a6f357b3f65b --- /dev/null +++ b/mesonbuild/modules/features/module.py @@ -0,0 +1,711 @@ +# Copyright (c) 2023, NumPy Developers. +import os +from typing import ( + Dict, Set, Tuple, List, Callable, Optional, + Union, Any, cast, TYPE_CHECKING +) +from ... import mlog, build +from ...compilers import Compiler +from ...mesonlib import File, MesonException +from ...interpreter.type_checking import NoneType +from ...interpreterbase.decorators import ( + noKwargs, KwargInfo, typed_kwargs, typed_pos_args, + ContainerTypeInfo, permittedKwargs +) +from .. import ModuleInfo, NewExtensionModule, ModuleObject +from .feature import FeatureObject, ConflictAttr +from .utils import test_code, get_compiler, generate_hash + +if TYPE_CHECKING: + from typing import TypedDict + from ...interpreterbase import TYPE_var, TYPE_kwargs + from .. import ModuleState + from .feature import FeatureKwArgs + + class TestKwArgs(TypedDict): + compiler: Optional[Compiler] + force_args: Optional[List[str]] + anyfet: bool + cached: bool + + class TestResultKwArgs(TypedDict): + target_name: str + prevalent_features: List[str] + features: List[str] + args: List[str] + detect: List[str] + defines: List[str] + undefines: List[str] + is_supported: bool + is_disabled: bool + fail_reason: str + +class TargetsObject(ModuleObject): + def __init__(self) -> None: + super().__init__() + self._targets: Dict[ + Union[FeatureObject, Tuple[FeatureObject, ...]], + List[build.StaticLibrary] + ] = {} + self._baseline: List[build.StaticLibrary] = [] + self.methods.update({ + 'static_lib': self.static_lib_method, + 'extend': self.extend_method + }) + + def extend_method(self, state: 'ModuleState', + args: List['TYPE_var'], + kwargs: 'TYPE_kwargs') -> 'TargetsObject': + + @typed_pos_args('feature.TargetsObject.extend', TargetsObject) + @noKwargs + def test_args(state: 'ModuleState', + args: Tuple[TargetsObject], + kwargs: 'TYPE_kwargs') -> TargetsObject: + return args[0] + robj: TargetsObject = test_args(state, args, kwargs) + self._baseline.extend(robj._baseline) + for features, robj_targets in robj._targets.items(): + targets: List[build.StaticLibrary] = self._targets.setdefault(features, []) + targets += robj_targets + return self + + @typed_pos_args('features.TargetsObject.static_lib', str) + @noKwargs + def static_lib_method(self, state: 'ModuleState', args: Tuple[str], + kwargs: 'TYPE_kwargs' + ) -> Any: + # The linking order must be based on the lowest interested features, + # to ensures that the linker prioritizes any duplicate weak global symbols + # of the lowest interested features over the highest ones, + # starting with the baseline to avoid any possible crashes due + # to any involved optimizations that may generated based + # on the highest interested features. + link_whole = [] + self._baseline + tcast = Union[FeatureObject, Tuple[FeatureObject, ...]] + for features in FeatureObject.sorted_multi(self._targets.keys()): + link_whole += self._targets[cast(tcast, features)] + if not link_whole: + return [] + static_lib = state._interpreter.func_static_lib( + None, [args[0]], { + 'link_whole': link_whole + } + ) + return static_lib + + def add_baseline_target(self, target: build.StaticLibrary) -> None: + self._baseline.append(target) + + def add_target(self, features: Union[FeatureObject, List[FeatureObject]], + target: build.StaticLibrary) -> None: + tfeatures = ( + features if isinstance(features, FeatureObject) + else tuple(sorted(features)) + ) + targets: List[build.StaticLibrary] = self._targets.setdefault( + tfeatures, cast(List[build.StaticLibrary], [])) # type: ignore + targets.append(target) + +class Module(NewExtensionModule): + INFO = ModuleInfo('features', '0.1.0') + def __init__(self) -> None: + super().__init__() + self.methods.update({ + 'new': self.new_method, + 'test': self.test_method, + 'implicit': self.implicit_method, + 'implicit_c': self.implicit_c_method, + 'sort': self.sort_method, + 'multi_targets': self.multi_targets_method, + }) + + def new_method(self, state: 'ModuleState', + args: List['TYPE_var'], + kwargs: 'TYPE_kwargs') -> FeatureObject: + return FeatureObject(state, args, kwargs) + + def _cache_dict(self, state: 'ModuleState' + ) -> Dict[str, 'TestResultKwArgs']: + coredata = state.environment.coredata + attr_name = 'module_features_cache' + if not hasattr(coredata, attr_name): + setattr(coredata, attr_name, {}) + return getattr(coredata, attr_name, {}) + + def _get_cache(self, state: 'ModuleState', key: str + ) -> Optional['TestResultKwArgs']: + return self._cache_dict(state).get(key) + + def _set_cache(self, state: 'ModuleState', key: str, + val: 'TestResultKwArgs') -> None: + self._cache_dict(state)[key] = val + + @typed_pos_args('features.test', varargs=FeatureObject, min_varargs=1) + @typed_kwargs('features.test', + KwargInfo('compiler', (NoneType, Compiler)), + KwargInfo('anyfet', bool, default = False), + KwargInfo('cached', bool, default = True), + KwargInfo( + 'force_args', (NoneType, str, ContainerTypeInfo(list, str)), + listify=True + ), + ) + def test_method(self, state: 'ModuleState', + args: Tuple[List[FeatureObject]], + kwargs: 'TestKwArgs' + ) -> List[Union[bool, 'TestResultKwArgs']]: + + features = args[0] + features_set = set(features) + anyfet = kwargs['anyfet'] + cached = kwargs['cached'] + compiler = kwargs.get('compiler') + if not compiler: + compiler = get_compiler(state) + + force_args = kwargs['force_args'] + if force_args is not None: + # removes in empty strings + force_args = [a for a in force_args if a] + + test_cached, test_result = self.cached_test( + state, features=features_set, + compiler=compiler, + anyfet=anyfet, + cached=cached, + force_args=force_args + ) + if not test_result['is_supported']: + if test_result['is_disabled']: + label = mlog.yellow('disabled') + else: + label = mlog.yellow('Unsupported') + else: + label = mlog.green('Supported') + if anyfet: + unsupported = ' '.join([ + fet.name for fet in sorted(features_set) + if fet.name not in test_result['features'] + ]) + if unsupported: + label = mlog.green(f'Parial support, missing({unsupported})') + + features_names = ' '.join([f.name for f in features]) + log_prefix = f'Test features "{mlog.bold(features_names)}" :' + cached_msg = f'({mlog.blue("cached")})' if test_cached else '' + if not test_result['is_supported']: + mlog.log(log_prefix, label, 'due to', test_result['fail_reason']) + else: + mlog.log(log_prefix, label, cached_msg) + return [test_result['is_supported'], test_result] + + def cached_test(self, state: 'ModuleState', + features: Set[FeatureObject], + compiler: 'Compiler', + force_args: Optional[List[str]], + anyfet: bool, cached: bool, + _caller: Optional[Set[FeatureObject]] = None + ) -> Tuple[bool, 'TestResultKwArgs']: + + if cached: + test_hash = generate_hash( + sorted(features), compiler, + anyfet, force_args + ) + test_result = self._get_cache(state, test_hash) + if test_result is not None: + return True, test_result + + if anyfet: + test_func = self.test_any + else: + test_func = self.test + + test_result = test_func( + state, features=features, + compiler=compiler, + force_args=force_args, + cached=cached, + _caller=_caller + ) + if cached: + self._set_cache(state, test_hash, test_result) + return False, test_result + + def test_any(self, state: 'ModuleState', features: Set[FeatureObject], + compiler: 'Compiler', + force_args: Optional[List[str]], + cached: bool, + # dummy no need for recrusive guard + _caller: Optional[Set[FeatureObject]] = None, + ) -> 'TestResultKwArgs': + + _, test_any_result = self.cached_test( + state, features=features, + compiler=compiler, + anyfet=False, + cached=cached, + force_args=force_args, + ) + if test_any_result['is_supported']: + return test_any_result + + all_features = sorted(FeatureObject.get_implicit_combine_multi(features)) + features_any = set() + for fet in all_features: + _, test_any_result = self.cached_test( + state, features={fet,}, + compiler=compiler, + cached=cached, + anyfet=False, + force_args=force_args, + ) + if test_any_result['is_supported']: + features_any.add(fet) + + _, test_any_result = self.cached_test( + state, features=features_any, + compiler=compiler, + cached=cached, + anyfet=False, + force_args=force_args, + ) + return test_any_result + + def test(self, state: 'ModuleState', features: Set[FeatureObject], + compiler: 'Compiler', + force_args: Optional[List[str]] = None, + cached: bool = True, + _caller: Optional[Set[FeatureObject]] = None + ) -> 'TestResultKwArgs': + + implied_features = FeatureObject.get_implicit_multi(features) + all_features = sorted(implied_features.union(features)) + # For multiple features, it important to erase any features + # implied by another to avoid duplicate testing since + # implied features already tested also we use this set to genrate + # unque target name that can be used for multiple targets + # build. + prevalent_features = sorted(features.difference(implied_features)) + if len(prevalent_features) == 0: + # It happens when all features imply each other. + # Set the highest interested feature + prevalent_features = sorted(features)[-1:] + + prevalent_names = [fet.name for fet in prevalent_features] + # prepare the result dict + test_result: 'TestResultKwArgs' = { + 'target_name': '__'.join(prevalent_names), + 'prevalent_features': prevalent_names, + 'features': [fet.name for fet in all_features], + 'args': [], + 'detect': [], + 'defines': [], + 'undefines': [], + 'is_supported': True, + 'is_disabled': False, + 'fail_reason': '', + } + def fail_result(fail_reason: str, is_disabled: bool = False + ) -> 'TestResultKwArgs': + test_result.update({ + 'features': [], + 'args': [], + 'detect': [], + 'defines': [], + 'undefines': [], + 'is_supported': False, + 'is_disabled': is_disabled, + 'fail_reason': fail_reason, + }) + return test_result + + # test any of prevalent features wither they disabled or not + for fet in prevalent_features: + if fet.disable: + return fail_result( + f'{fet.name} is disabled due to "{fet.disable}"', + True + ) + + # since we allows features to imply each other + # items of `features` may part of `implied_features` + if _caller is None: + _caller = set() + _caller = _caller.union(prevalent_features) + predecessor_features = implied_features.difference(_caller) + for fet in sorted(predecessor_features): + _, pred_result = self.cached_test( + state, features={fet,}, + compiler=compiler, + cached=cached, + anyfet=False, + force_args=force_args, + _caller=_caller, + ) + if not pred_result['is_supported']: + reason = f'Implied feature "{fet.name}" ' + pred_disabled = pred_result['is_disabled'] + if pred_disabled: + fail_reason = reason + 'is disabled' + else: + fail_reason = reason + 'is not supported' + return fail_result(fail_reason, pred_disabled) + + for k in ['defines', 'undefines']: + def_values = test_result[k] # type: ignore + pred_values = pred_result[k] # type: ignore + def_values += [v for v in pred_values if v not in def_values] + + # Sort based on the lowest interest to deal with conflict attributes + # when combine all attributes togathers + conflict_attrs = ['detect'] + if force_args is None: + conflict_attrs += ['args'] + else: + test_result['args'] = force_args + + for fet in all_features: + for attr in conflict_attrs: + values: List[ConflictAttr] = getattr(fet, attr) + accumulate_values = test_result[attr] # type: ignore + for conflict in values: + conflict_vals: List[str] = [] + # select the acc items based on the match + new_acc: List[str] = [] + for acc in accumulate_values: + # not affected by the match so we keep it + if not (conflict.match and conflict.match.match(acc)): + new_acc.append(acc) + continue + # no filter so we totaly escape it + if not conflict.mfilter: + continue + filter_val = conflict.mfilter.findall(acc) + filter_val = [ + conflict.mjoin.join([i for i in val if i]) + if isinstance(val, tuple) else val + for val in filter_val if val + ] + # no filter match so we totaly escape it + if not filter_val: + continue + conflict_vals.append(conflict.mjoin.join(filter_val)) + new_acc.append(conflict.val + conflict.mjoin.join(conflict_vals)) + accumulate_values = test_result[attr] = new_acc # type: ignore + + test_args = compiler.has_multi_arguments + args = test_result['args'] + if args: + supported_args, test_cached = test_args(args, state.environment) + if not supported_args: + return fail_result( + f'Arguments "{", ".join(args)}" are not supported' + ) + + for fet in prevalent_features: + if fet.test_code: + _, tested_code, _ = test_code( + state, compiler, args, fet.test_code + ) + if not tested_code: + return fail_result( + f'Compiler fails against the test code of "{fet.name}"' + ) + + test_result['defines'] += [fet.name] + fet.group + for extra_name, extra_test in fet.extra_tests.items(): + _, tested_code, _ = test_code( + state, compiler, args, extra_test + ) + k = 'defines' if tested_code else 'undefines' + test_result[k].append(extra_name) # type: ignore + return test_result + + @permittedKwargs(build.known_stlib_kwargs | { + 'dispatch', 'baseline', 'prefix', 'cached', 'keep_sort' + }) + @typed_pos_args('features.multi_targets', str, min_varargs=1, varargs=( + str, File, build.CustomTarget, build.CustomTargetIndex, + build.GeneratedList, build.StructuredSources, build.ExtractedObjects, + build.BuildTarget + )) + @typed_kwargs('features.multi_targets', + KwargInfo( + 'dispatch', ( + ContainerTypeInfo(list, (FeatureObject, list)), + ), + default=[] + ), + KwargInfo( + 'baseline', ( + NoneType, + ContainerTypeInfo(list, FeatureObject) + ) + ), + KwargInfo('prefix', str, default=''), + KwargInfo('compiler', (NoneType, Compiler)), + KwargInfo('cached', bool, default = True), + KwargInfo('keep_sort', bool, default = False), + allow_unknown=True + ) + def multi_targets_method(self, state: 'ModuleState', + args: Tuple[str], kwargs: 'TYPE_kwargs' + ) -> TargetsObject: + config_name = args[0] + sources = args[1] # type: ignore + dispatch: List[Union[FeatureObject, List[FeatureObject]]] = ( + kwargs.pop('dispatch') # type: ignore + ) + baseline: Optional[List[FeatureObject]] = ( + kwargs.pop('baseline') # type: ignore + ) + prefix: str = kwargs.pop('prefix') # type: ignore + cached: bool = kwargs.pop('cached') # type: ignore + compiler: Optional[Compiler] = kwargs.pop('compiler') # type: ignore + if not compiler: + compiler = get_compiler(state) + + baseline_features : Set[FeatureObject] = set() + has_baseline = baseline is not None + if has_baseline: + baseline_features = FeatureObject.get_implicit_combine_multi(baseline) + _, baseline_test_result = self.cached_test( + state, features=set(baseline), + anyfet=True, cached=cached, + compiler=compiler, + force_args=None + ) + + enabled_targets_names: List[str] = [] + enabled_targets_features: List[Union[ + FeatureObject, List[FeatureObject] + ]] = [] + enabled_targets_tests: List['TestResultKwArgs'] = [] + skipped_targets: List[Tuple[ + Union[FeatureObject, List[FeatureObject]], str + ]] = [] + for d in dispatch: + if isinstance(d, FeatureObject): + target = {d,} + is_base_part = d in baseline_features + else: + target = set(d) + is_base_part = all(f in baseline_features for f in d) + + if is_base_part: + skipped_targets.append((d, "part of baseline features")) + continue + _, test_result = self.cached_test( + state=state, features=target, + anyfet=False, cached=cached, + compiler=compiler, + force_args=None + ) + if not test_result['is_supported']: + skipped_targets.append( + (d, test_result['fail_reason']) + ) + continue + target_name = test_result['target_name'] + if target_name in enabled_targets_names: + skipped_targets.append(( + d, f'Dublicate target name "{target_name}"' + )) + continue + enabled_targets_names.append(target_name) + enabled_targets_features.append(d) + enabled_targets_tests.append(test_result) + + if not kwargs.pop('keep_sort'): + enabled_targets_sorted = FeatureObject.sorted_multi(enabled_targets_features, reverse=True) + if enabled_targets_features != enabled_targets_sorted: + log_targets = FeatureObject.features_names(enabled_targets_features) + log_targets_sorted = FeatureObject.features_names(enabled_targets_sorted) + raise MesonException( + 'The enabled dispatch features should be sorted based on the highest interest:\n' + f'Expected: {log_targets_sorted}\n' + f'Got: {log_targets}\n' + 'Note: This validation may not be accurate when dealing with multi-features ' + 'per single target.\n' + 'You can keep the current sort and bypass this validation by passing ' + 'the argument "keep_sort: true".' + ) + + config_path = self.gen_config( + state, + config_name=config_name, + targets=enabled_targets_tests, + prefix=prefix, + has_baseline=has_baseline + ) + mtargets_obj = TargetsObject() + if has_baseline: + mtargets_obj.add_baseline_target( + self.gen_target( + state=state, config_name=config_name, + sources=sources, test_result=baseline_test_result, + prefix=prefix, is_baseline=True, + stlib_kwargs=kwargs + ) + ) + for features_objects, target_test in zip(enabled_targets_features, enabled_targets_tests): + static_lib = self.gen_target( + state=state, config_name=config_name, + sources=sources, test_result=target_test, + prefix=prefix, is_baseline=False, + stlib_kwargs=kwargs + ) + mtargets_obj.add_target(features_objects, static_lib) + + skipped_targets_info: List[str] = [] + skipped_tab = ' '*4 + for skipped, reason in skipped_targets: + name = ', '.join( + [skipped.name] if isinstance(skipped, FeatureObject) + else [fet.name for fet in skipped] + ) + skipped_targets_info.append(f'{skipped_tab}"{name}": "{reason}"') + + target_info: Callable[[str, 'TestResultKwArgs'], str] = lambda target_name, test_result: ( + f'{skipped_tab}"{target_name}":\n' + '\n'.join([ + f'{skipped_tab*2}"{k}": {v}' + for k, v in test_result.items() + ]) + ) + enabled_targets_info: List[str] = [ + target_info(test_result['target_name'], test_result) + for test_result in enabled_targets_tests + ] + if has_baseline: + enabled_targets_info.append(target_info( + f'baseline({baseline_test_result["target_name"]})', + baseline_test_result + )) + enabled_targets_names += ['baseline'] + + mlog.log( + f'Generating multi-targets for "{mlog.bold(config_name)}"', + '\n Enabled targets:', + mlog.green(', '.join(enabled_targets_names)) + ) + mlog.debug( + f'Generating multi-targets for "{config_name}"', + '\n Config path:', config_path, + '\n Enabled targets:', + '\n'+'\n'.join(enabled_targets_info), + '\n Skipped targets:', + '\n'+'\n'.join(skipped_targets_info), + '\n' + ) + return mtargets_obj + + def gen_target(self, state: 'ModuleState', config_name: str, + sources: List[Union[ + str, File, build.CustomTarget, build.CustomTargetIndex, + build.GeneratedList, build.StructuredSources, build.ExtractedObjects, + build.BuildTarget + ]], + test_result: 'TestResultKwArgs', + prefix: str, is_baseline: bool, + stlib_kwargs: Dict[str, Any] + ) -> build.StaticLibrary: + + target_name = 'baseline' if is_baseline else test_result['target_name'] + args = [f'-D{prefix}HAVE_{df}' for df in test_result['defines']] + args += test_result['args'] + if is_baseline: + args.append(f'-D{prefix}MTARGETS_BASELINE') + else: + args.append(f'-D{prefix}MTARGETS_CURRENT={target_name}') + stlib_kwargs = stlib_kwargs.copy() + stlib_kwargs.update({ + 'sources': sources, + 'c_args': stlib_kwargs.get('c_args', []) + args, + 'cpp_args': stlib_kwargs.get('cpp_args', []) + args + }) + static_lib: build.StaticLibrary = state._interpreter.func_static_lib( + None, [config_name + '_' + target_name], + stlib_kwargs + ) + return static_lib + + def gen_config(self, state: 'ModuleState', config_name: str, + targets: List['TestResultKwArgs'], + prefix: str, has_baseline: bool + ) -> str: + + dispatch_calls: List[str] = [] + for test in targets: + c_detect = '&&'.join([ + f'TEST_CB({d})' for d in test['detect'] + ]) + if c_detect: + c_detect = f'({c_detect})' + else: + c_detect = '1' + dispatch_calls.append( + f'{prefix}_MTARGETS_EXPAND(' + f'EXEC_CB({c_detect}, {test["target_name"]}, __VA_ARGS__)' + ')' + ) + + config_file = [ + '/* Autogenerated by the Meson features module. */', + '/* Do not edit, your changes will be lost. */', + '', + f'#undef {prefix}_MTARGETS_EXPAND', + f'#define {prefix}_MTARGETS_EXPAND(X) X', + '', + f'#undef {prefix}MTARGETS_CONF_BASELINE', + f'#define {prefix}MTARGETS_CONF_BASELINE(EXEC_CB, ...) ' + ( + f'{prefix}_MTARGETS_EXPAND(EXEC_CB(__VA_ARGS__))' + if has_baseline else '' + ), + '', + f'#undef {prefix}MTARGETS_CONF_DISPATCH', + f'#define {prefix}MTARGETS_CONF_DISPATCH(TEST_CB, EXEC_CB, ...) \\', + ' \\\n'.join(dispatch_calls), + '', + ] + + build_dir = state.environment.build_dir + sub_dir = state.subdir + if sub_dir: + build_dir = os.path.join(build_dir, sub_dir) + config_path = os.path.abspath(os.path.join(build_dir, config_name)) + + os.makedirs(os.path.dirname(config_path), exist_ok=True) + with open(config_path, "w", encoding='utf-8') as cout: + cout.write('\n'.join(config_file)) + + return config_path + + @typed_pos_args('features.sort', varargs=FeatureObject, min_varargs=1) + @typed_kwargs('features.sort', + KwargInfo('reverse', bool, default = False), + ) + def sort_method(self, state: 'ModuleState', + args: Tuple[List[FeatureObject]], + kwargs: Dict[str, bool] + ) -> List[FeatureObject]: + return sorted(args[0], reverse=kwargs['reverse']) + + @typed_pos_args('features.implicit', varargs=FeatureObject, min_varargs=1) + @noKwargs + def implicit_method(self, state: 'ModuleState', + args: Tuple[List[FeatureObject]], + kwargs: 'TYPE_kwargs' + ) -> List[FeatureObject]: + + features = args[0] + return sorted(FeatureObject.get_implicit_multi(features)) + + @typed_pos_args('features.implicit', varargs=FeatureObject, min_varargs=1) + @noKwargs + def implicit_c_method(self, state: 'ModuleState', + args: Tuple[List[FeatureObject]], + kwargs: 'TYPE_kwargs' + ) -> List[FeatureObject]: + return sorted(FeatureObject.get_implicit_combine_multi(args[0])) diff --git a/mesonbuild/modules/features/utils.py b/mesonbuild/modules/features/utils.py new file mode 100644 index 000000000000..88eb19d82d92 --- /dev/null +++ b/mesonbuild/modules/features/utils.py @@ -0,0 +1,39 @@ +# Copyright (c) 2023, NumPy Developers. +import hashlib +from typing import Tuple, List, Union, Any, TYPE_CHECKING +from ...mesonlib import MesonException, MachineChoice + +if TYPE_CHECKING: + from ...compilers import Compiler + from ...mesonlib import File + from .. import ModuleState + +def get_compiler(state: 'ModuleState') -> 'Compiler': + for_machine = MachineChoice.HOST + clist = state.environment.coredata.compilers[for_machine] + for cstr in ('c', 'cpp'): + try: + compiler = clist[cstr] + break + except KeyError: + raise MesonException( + 'Unable to get compiler for C or C++ language ' + 'try to specify a valid C/C++ compiler via option "compiler".' + ) + return compiler + +def test_code(state: 'ModuleState', compiler: 'Compiler', + args: List[str], code: 'Union[str, File]' + ) -> Tuple[bool, bool, str]: + # TODO: Add option to treat warnings as errors + with compiler.cached_compile( + code, state.environment.coredata, extra_args=args + ) as p: + return p.cached, p.returncode == 0, p.stderr + +def generate_hash(*args: Any) -> str: + hasher = hashlib.sha1() + test: List[bytes] = [] + for a in args: + hasher.update(bytes(str(a), encoding='utf-8')) + return hasher.hexdigest() diff --git a/run_mypy.py b/run_mypy.py index 975232a48624..8b250b3e5ebc 100755 --- a/run_mypy.py +++ b/run_mypy.py @@ -77,6 +77,7 @@ 'mesonbuild/modules/sourceset.py', 'mesonbuild/modules/wayland.py', 'mesonbuild/modules/windows.py', + 'mesonbuild/modules/features/', 'mesonbuild/mparser.py', 'mesonbuild/msetup.py', 'mesonbuild/mtest.py', diff --git a/run_unittests.py b/run_unittests.py index 84edb34ccd48..4a784dc07318 100755 --- a/run_unittests.py +++ b/run_unittests.py @@ -39,6 +39,7 @@ from unittests.subprojectscommandtests import SubprojectsCommandTests from unittests.windowstests import WindowsTests from unittests.platformagnostictests import PlatformAgnosticTests +from unittests.featurestests import FeaturesTests def unset_envs(): # For unit tests we must fully control all command lines @@ -108,7 +109,7 @@ def main(): 'TAPParserTests', 'SubprojectsCommandTests', 'PlatformAgnosticTests', 'LinuxlikeTests', 'LinuxCrossArmTests', 'LinuxCrossMingwTests', - 'WindowsTests', 'DarwinTests'] + 'WindowsTests', 'DarwinTests', 'FeaturesTests'] try: import pytest # noqa: F401 diff --git a/test cases/features/1 baseline/baseline.c b/test cases/features/1 baseline/baseline.c new file mode 100644 index 000000000000..c208e9bcc1ac --- /dev/null +++ b/test cases/features/1 baseline/baseline.c @@ -0,0 +1,77 @@ +// the headers files of enabled CPU features +#ifdef HAVE_SSE + #include +#endif +#ifdef HAVE_SSE2 + #include +#endif +#ifdef HAVE_SSE3 + #include +#endif +#ifdef HAVE_SSSE3 + #include +#endif +#ifdef HAVE_SSE41 + #include +#endif +#ifdef HAVE_NEON + #include +#endif + +int main() { +#if defined( __i386__ ) || defined(i386) || defined(_M_IX86) || \ + defined(__x86_64__) || defined(__amd64__) || defined(__x86_64) || defined(_M_AMD64) + #ifndef HAVE_SSE + #error "expected SSE to be enabled" + #endif + #ifndef HAVE_SSE2 + #error "expected SSE2 to be enabled" + #endif + #ifndef HAVE_SSE3 + #error "expected SSE3 to be enabled" + #endif +#else + #ifdef HAVE_SSE + #error "expected SSE to be disabled" + #endif + #ifdef HAVE_SSE2 + #error "expected SSE2 to be disabled" + #endif + #ifdef HAVE_SSE3 + #error "expected SSE3 to be disabled" + #endif +#endif + +#if defined(__arm__) + #ifndef HAVE_NEON + #error "expected NEON to be enabled" + #endif +#else + #ifdef HAVE_NEON + #error "expected NEON to be disabled" + #endif +#endif + +#if defined(__aarch64__) || defined(_M_ARM64) + #ifndef HAVE_NEON_FP16 + #error "expected NEON_FP16 to be enabled" + #endif + #ifndef HAVE_NEON_VFPV4 + #error "expected NEON_VFPV4 to be enabled" + #endif + #ifndef HAVE_ASIMD + #error "expected ASIMD to be enabled" + #endif +#else + #ifdef HAVE_NEON_FP16 + #error "expected NEON_FP16 to be disabled" + #endif + #ifdef HAVE_NEON_VFPV4 + #error "expected NEON_VFPV4 to be disabled" + #endif + #ifdef HAVE_ASIMD + #error "expected ASIMD to be disabled" + #endif +#endif + return 0; +} diff --git a/test cases/features/1 baseline/init_features b/test cases/features/1 baseline/init_features new file mode 120000 index 000000000000..d52da150db76 --- /dev/null +++ b/test cases/features/1 baseline/init_features @@ -0,0 +1 @@ +../init_features \ No newline at end of file diff --git a/test cases/features/1 baseline/meson.build b/test cases/features/1 baseline/meson.build new file mode 100644 index 000000000000..71c4299cf3d4 --- /dev/null +++ b/test cases/features/1 baseline/meson.build @@ -0,0 +1,14 @@ +project('baseline', 'c') +subdir('init_features') + +baseline = mod_features.test(SSE3, NEON, anyfet: true) +message(baseline) +baseline_args = baseline[1]['args'] +foreach def : baseline[1]['defines'] + baseline_args += ['-DHAVE_' + def] +endforeach +add_project_arguments(baseline_args, language: ['c', 'cpp']) + +exe = executable('baseline', 'baseline.c') +test('baseline', exe) + diff --git a/test cases/features/2 multi_targets/dispatch.h b/test cases/features/2 multi_targets/dispatch.h new file mode 100644 index 000000000000..d1e00db0f164 --- /dev/null +++ b/test cases/features/2 multi_targets/dispatch.h @@ -0,0 +1,90 @@ +#ifndef DISPATCH_H_ +#define DISPATCH_H_ + +// the headers files of enabled CPU features +#ifdef HAVE_SSE + #include +#endif +#ifdef HAVE_SSE2 + #include +#endif +#ifdef HAVE_SSE3 + #include +#endif +#ifdef HAVE_SSSE3 + #include +#endif +#ifdef HAVE_SSE41 + #include +#endif +#ifdef HAVE_NEON + #include +#endif + +#if defined( __i386__ ) || defined(i386) || defined(_M_IX86) || \ + defined(__x86_64__) || defined(__amd64__) || defined(__x86_64) || defined(_M_AMD64) + #define TEST_X86 +#elif defined(__aarch64__) || defined(_M_ARM64) + #define TEST_ARM64 +#elif defined(__arm__) + #define TEST_ARM +#endif + +enum { + CPU_SSE = 1, + CPU_SSE2, + CPU_SSE3, + CPU_SSSE3, + CPU_SSE41, + CPU_NEON, + CPU_NEON_FP16, + CPU_NEON_VFPV4, + CPU_ASIMD +}; +int cpu_has(int feature_id); +#define CPU_TEST(FEATURE_NAME) cpu_has(CPU_##FEATURE_NAME) +#define CPU_TEST_DUMMY(FEATURE_NAME) + +#define EXPAND(X) X +#define CAT__(A, B) A ## B +#define CAT_(A, B) CAT__(A, B) +#define CAT(A, B) CAT_(A, B) +#define STRINGIFY(x) #x +#define TOSTRING(x) STRINGIFY(x) + +#ifdef MTARGETS_CURRENT + #define DISPATCH_CURRENT(X) CAT(CAT(X,_), MTARGETS_CURRENT) +#else + // baseline + #define DISPATCH_CURRENT(X) X +#endif + +#define DISPATCH_DECLARE(...) \ + MTARGETS_CONF_DISPATCH(CPU_TEST_DUMMY, DISPATCH_DECLARE_CB, __VA_ARGS__) \ + MTARGETS_CONF_BASELINE(DISPATCH_DECLARE_BASE_CB, __VA_ARGS__) + +// Preprocessor callbacks +#define DISPATCH_DECLARE_CB(TESTED_FEATURES_DUMMY, TARGET_NAME, LEFT, ...) \ + CAT(CAT(LEFT, _), TARGET_NAME) __VA_ARGS__; +#define DISPATCH_DECLARE_BASE_CB(LEFT, ...) \ + LEFT __VA_ARGS__; + +#define DISPATCH_CALL(NAME) \ + ( \ + MTARGETS_CONF_DISPATCH(CPU_TEST, DISPATCH_CALL_CB, NAME) \ + MTARGETS_CONF_BASELINE(DISPATCH_CALL_BASE_CB, NAME) \ + NULL \ + ) +// Preprocessor callbacks +#define DISPATCH_CALL_CB(TESTED_FEATURES, TARGET_NAME, LEFT) \ + (TESTED_FEATURES) ? CAT(CAT(LEFT, _), TARGET_NAME) : +#define DISPATCH_CALL_BASE_CB(LEFT) \ + (1) ? LEFT : + +#include "dispatch1.conf.h" +DISPATCH_DECLARE(const char *dispatch1, ()) + +#include "dispatch2.conf.h" +DISPATCH_DECLARE(const char *dispatch2, ()) + +#endif // DISPATCH_H_ diff --git a/test cases/features/2 multi_targets/dispatch1.c b/test cases/features/2 multi_targets/dispatch1.c new file mode 100644 index 000000000000..b4463355e2a5 --- /dev/null +++ b/test cases/features/2 multi_targets/dispatch1.c @@ -0,0 +1,28 @@ +#include "dispatch.h" + +const char *DISPATCH_CURRENT(dispatch1)() +{ +#ifdef HAVE_SSSE3 + #ifndef HAVE_SSE3 + #error "expected a defention for implied features" + #endif + #ifndef HAVE_SSE2 + #error "expected a defention for implied features" + #endif + #ifndef HAVE_SSE + #error "expected a defention for implied features" + #endif +#endif +#ifdef HAVE_ASIMD + #ifndef HAVE_NEON + #error "expected a defention for implied features" + #endif + #ifndef HAVE_NEON_FP16 + #error "expected a defention for implied features" + #endif + #ifndef HAVE_NEON_VFPV4 + #error "expected a defention for implied features" + #endif +#endif + return TOSTRING(DISPATCH_CURRENT(dispatch1)); +} diff --git a/test cases/features/2 multi_targets/dispatch2.c b/test cases/features/2 multi_targets/dispatch2.c new file mode 100644 index 000000000000..7a69fc3d0375 --- /dev/null +++ b/test cases/features/2 multi_targets/dispatch2.c @@ -0,0 +1,21 @@ +#include "dispatch.h" + +const char *DISPATCH_CURRENT(dispatch2)() +{ +#ifdef HAVE_SSE41 + #ifndef HAVE_SSSE3 + #error "expected a defention for implied features" + #endif + #ifndef HAVE_SSE3 + #error "expected a defention for implied features" + #endif + #ifndef HAVE_SSE2 + #error "expected a defention for implied features" + #endif + #ifndef HAVE_SSE + #error "expected a defention for implied features" + #endif +#endif + return TOSTRING(DISPATCH_CURRENT(dispatch2)); +} + diff --git a/test cases/features/2 multi_targets/dispatch3.c b/test cases/features/2 multi_targets/dispatch3.c new file mode 100644 index 000000000000..a3a555af2ca7 --- /dev/null +++ b/test cases/features/2 multi_targets/dispatch3.c @@ -0,0 +1 @@ +#error "no targets enabled for this source" diff --git a/test cases/features/2 multi_targets/init_features b/test cases/features/2 multi_targets/init_features new file mode 120000 index 000000000000..d52da150db76 --- /dev/null +++ b/test cases/features/2 multi_targets/init_features @@ -0,0 +1 @@ +../init_features \ No newline at end of file diff --git a/test cases/features/2 multi_targets/main.c b/test cases/features/2 multi_targets/main.c new file mode 100644 index 000000000000..88ea11ae767c --- /dev/null +++ b/test cases/features/2 multi_targets/main.c @@ -0,0 +1,45 @@ +#include "dispatch.h" +#include +#include + +int cpu_has(int feature_id) +{ + // we assume the used features are supported by CPU + return 1; +} + +int main() +{ + #include "dispatch1.conf.h" + const char *dispatch1_str = DISPATCH_CALL(dispatch1)(); +#if defined(TEST_X86) + const char *exp_dispatch1_str = "dispatch1_SSSE3"; +#elif defined(TEST_ARM64) + const char *exp_dispatch1_str = "dispatch1"; +#elif defined(TEST_ARM) + const char *exp_dispatch1_str = "dispatch1_ASIMD"; +#else + const char *exp_dispatch1_str = "dispatch1"; +#endif + if (strcmp(dispatch1_str, exp_dispatch1_str) != 0) { + return 1; + } + #include "dispatch2.conf.h" + const char *dispatch2_str = DISPATCH_CALL(dispatch2)(); +#if defined(TEST_X86) + const char *exp_dispatch2_str = "dispatch2_SSE41"; +#elif defined(TEST_ARM64) || defined(TEST_ARM) + const char *exp_dispatch2_str = "dispatch2_ASIMD"; +#else + const char *exp_dispatch2_str = "dispatch2"; +#endif + if (strcmp(dispatch2_str, exp_dispatch2_str) != 0) { + return 2; + } + #include "dispatch3.conf.h" + const char *dispatch3_str = DISPATCH_CALL(dispatch3); + if (dispatch3_str != NULL) { + return 3; + } + return 0; +} diff --git a/test cases/features/2 multi_targets/meson.build b/test cases/features/2 multi_targets/meson.build new file mode 100644 index 000000000000..ffceda098f1a --- /dev/null +++ b/test cases/features/2 multi_targets/meson.build @@ -0,0 +1,26 @@ +project('multi_targets', 'c') +subdir('init_features') + +multi_targets = mod_features.multi_targets( + 'dispatch1.conf.h', 'dispatch1.c', + dispatch: [SSSE3, ASIMD], + baseline: [SSE3, NEON] +) + +multi_targets.extend(mod_features.multi_targets( + 'dispatch2.conf.h', 'dispatch2.c', + dispatch: [SSE41, SSSE3, ASIMD], + baseline: [SSE3] +)) + +multi_targets.extend(mod_features.multi_targets( + 'dispatch3.conf.h', 'dispatch3.c', + dispatch: [] +)) + +exe = executable( + 'multi_targets', 'main.c', + link_with: multi_targets.static_lib('multi_targets_lib') +) + +test('multi_targets', exe) diff --git a/test cases/features/init_features/checks/cpu_asimd.c b/test cases/features/init_features/checks/cpu_asimd.c new file mode 100644 index 000000000000..6bc9022a58d3 --- /dev/null +++ b/test cases/features/init_features/checks/cpu_asimd.c @@ -0,0 +1,27 @@ +#ifdef _MSC_VER + #include +#endif +#include + +int main(int argc, char **argv) +{ + float *src = (float*)argv[argc-1]; + float32x4_t v1 = vdupq_n_f32(src[0]), v2 = vdupq_n_f32(src[1]); + /* MAXMIN */ + int ret = (int)vgetq_lane_f32(vmaxnmq_f32(v1, v2), 0); + ret += (int)vgetq_lane_f32(vminnmq_f32(v1, v2), 0); + /* ROUNDING */ + ret += (int)vgetq_lane_f32(vrndq_f32(v1), 0); +#ifdef __aarch64__ + { + double *src2 = (double*)argv[argc-1]; + float64x2_t vd1 = vdupq_n_f64(src2[0]), vd2 = vdupq_n_f64(src2[1]); + /* MAXMIN */ + ret += (int)vgetq_lane_f64(vmaxnmq_f64(vd1, vd2), 0); + ret += (int)vgetq_lane_f64(vminnmq_f64(vd1, vd2), 0); + /* ROUNDING */ + ret += (int)vgetq_lane_f64(vrndq_f64(vd1), 0); + } +#endif + return ret; +} diff --git a/test cases/features/init_features/checks/cpu_neon.c b/test cases/features/init_features/checks/cpu_neon.c new file mode 100644 index 000000000000..8c64f864dea6 --- /dev/null +++ b/test cases/features/init_features/checks/cpu_neon.c @@ -0,0 +1,19 @@ +#ifdef _MSC_VER + #include +#endif +#include + +int main(int argc, char **argv) +{ + // passing from untraced pointers to avoid optimizing out any constants + // so we can test against the linker. + float *src = (float*)argv[argc-1]; + float32x4_t v1 = vdupq_n_f32(src[0]), v2 = vdupq_n_f32(src[1]); + int ret = (int)vgetq_lane_f32(vmulq_f32(v1, v2), 0); +#ifdef __aarch64__ + double *src2 = (double*)argv[argc-2]; + float64x2_t vd1 = vdupq_n_f64(src2[0]), vd2 = vdupq_n_f64(src2[1]); + ret += (int)vgetq_lane_f64(vmulq_f64(vd1, vd2), 0); +#endif + return ret; +} diff --git a/test cases/features/init_features/checks/cpu_neon_fp16.c b/test cases/features/init_features/checks/cpu_neon_fp16.c new file mode 100644 index 000000000000..f3b949770db6 --- /dev/null +++ b/test cases/features/init_features/checks/cpu_neon_fp16.c @@ -0,0 +1,11 @@ +#ifdef _MSC_VER + #include +#endif +#include + +int main(int argc, char **argv) +{ + short *src = (short*)argv[argc-1]; + float32x4_t v_z4 = vcvt_f32_f16((float16x4_t)vld1_s16(src)); + return (int)vgetq_lane_f32(v_z4, 0); +} diff --git a/test cases/features/init_features/checks/cpu_neon_vfpv4.c b/test cases/features/init_features/checks/cpu_neon_vfpv4.c new file mode 100644 index 000000000000..a039159ddeed --- /dev/null +++ b/test cases/features/init_features/checks/cpu_neon_vfpv4.c @@ -0,0 +1,21 @@ +#ifdef _MSC_VER + #include +#endif +#include + +int main(int argc, char **argv) +{ + float *src = (float*)argv[argc-1]; + float32x4_t v1 = vdupq_n_f32(src[0]); + float32x4_t v2 = vdupq_n_f32(src[1]); + float32x4_t v3 = vdupq_n_f32(src[2]); + int ret = (int)vgetq_lane_f32(vfmaq_f32(v1, v2, v3), 0); +#ifdef __aarch64__ + double *src2 = (double*)argv[argc-2]; + float64x2_t vd1 = vdupq_n_f64(src2[0]); + float64x2_t vd2 = vdupq_n_f64(src2[1]); + float64x2_t vd3 = vdupq_n_f64(src2[2]); + ret += (int)vgetq_lane_f64(vfmaq_f64(vd1, vd2, vd3), 0); +#endif + return ret; +} diff --git a/test cases/features/init_features/checks/cpu_sse.c b/test cases/features/init_features/checks/cpu_sse.c new file mode 100644 index 000000000000..bb98bf63c0b9 --- /dev/null +++ b/test cases/features/init_features/checks/cpu_sse.c @@ -0,0 +1,7 @@ +#include + +int main(void) +{ + __m128 a = _mm_add_ps(_mm_setzero_ps(), _mm_setzero_ps()); + return (int)_mm_cvtss_f32(a); +} diff --git a/test cases/features/init_features/checks/cpu_sse2.c b/test cases/features/init_features/checks/cpu_sse2.c new file mode 100644 index 000000000000..658afc9b4abf --- /dev/null +++ b/test cases/features/init_features/checks/cpu_sse2.c @@ -0,0 +1,7 @@ +#include + +int main(void) +{ + __m128i a = _mm_add_epi16(_mm_setzero_si128(), _mm_setzero_si128()); + return _mm_cvtsi128_si32(a); +} diff --git a/test cases/features/init_features/checks/cpu_sse3.c b/test cases/features/init_features/checks/cpu_sse3.c new file mode 100644 index 000000000000..aece1e60174c --- /dev/null +++ b/test cases/features/init_features/checks/cpu_sse3.c @@ -0,0 +1,7 @@ +#include + +int main(void) +{ + __m128 a = _mm_hadd_ps(_mm_setzero_ps(), _mm_setzero_ps()); + return (int)_mm_cvtss_f32(a); +} diff --git a/test cases/features/init_features/checks/cpu_sse41.c b/test cases/features/init_features/checks/cpu_sse41.c new file mode 100644 index 000000000000..bfdb9feacc47 --- /dev/null +++ b/test cases/features/init_features/checks/cpu_sse41.c @@ -0,0 +1,7 @@ +#include + +int main(void) +{ + __m128 a = _mm_floor_ps(_mm_setzero_ps()); + return (int)_mm_cvtss_f32(a); +} diff --git a/test cases/features/init_features/checks/cpu_ssse3.c b/test cases/features/init_features/checks/cpu_ssse3.c new file mode 100644 index 000000000000..ad0abc1e66fb --- /dev/null +++ b/test cases/features/init_features/checks/cpu_ssse3.c @@ -0,0 +1,7 @@ +#include + +int main(void) +{ + __m128i a = _mm_hadd_epi16(_mm_setzero_si128(), _mm_setzero_si128()); + return (int)_mm_cvtsi128_si32(a); +} diff --git a/test cases/features/init_features/meson.build b/test cases/features/init_features/meson.build new file mode 100644 index 000000000000..c0b4f13fa862 --- /dev/null +++ b/test cases/features/init_features/meson.build @@ -0,0 +1,98 @@ +#project('test-features', 'c') +mod_features = import('features') +cpu_family = host_machine.cpu_family() +compiler_id = meson.get_compiler('c').get_id() +source_root = meson.project_source_root() + '/../init_features/' +# Basic X86 Features +# ------------------ +SSE = mod_features.new( + 'SSE', 1, args: '-msse', + test_code: files(source_root + 'checks/cpu_sse.c')[0] +) +SSE2 = mod_features.new( + 'SSE2', 2, implies: SSE, + args: '-msse2', + test_code: files(source_root + 'checks/cpu_sse2.c')[0] +) +# enabling SSE without SSE2 is useless also +# it's non-optional for x86_64 +SSE.update(implies: SSE2) +SSE3 = mod_features.new( + 'SSE3', 3, implies: SSE2, + args: '-msse3', + test_code: files(source_root + 'checks/cpu_sse3.c')[0] +) +SSSE3 = mod_features.new( + 'SSSE3', 4, implies: SSE3, + args: '-mssse3', + test_code: files(source_root + 'checks/cpu_ssse3.c')[0] +) +SSE41 = mod_features.new( + 'SSE41', 5, implies: SSSE3, + args: '-msse4.1', + test_code: files(source_root + 'checks/cpu_sse41.c')[0] +) +if cpu_family not in ['x86', 'x86_64'] + # should disable any prevalent features + SSE.update(disable: 'not supported by the current platform') +endif +# Specializations for non unix-like compilers +if compiler_id == 'intel-cl' + foreach fet : [SSE, SSE2, SSE3, SSSE3] + fet.update(args: {'val': '/arch:' + fet.get('name'), 'match': '/arch:.*'}) + endforeach + SSE41.update(args: {'val': '/arch:SSE4.1', 'match': '/arch:.*'}) +elif compiler_id == 'msvc' + # only available on 32-bit. Its enabled by default on 64-bit mode + foreach fet : [SSE, SSE2] + if cpu_family == 'x86' + fet.update(args: {'val': '/arch:' + fet.get('name'), 'match': clear_arch}) + else + fet.update(args: '') + endif + endforeach + # The following features don't own private FLAGS still + # the compiler provides ISA capability for them. + foreach fet : [SSE3, SSSE3, SSE41] + fet.update(args: '') + endforeach +endif + +# Basic ARM Features +# ------------------ +NEON = mod_features.new( + 'NEON', 200, + test_code: files(source_root + 'checks/cpu_neon.c')[0] +) +NEON_FP16 = mod_features.new( + 'NEON_FP16', 201, implies: NEON, + test_code: files(source_root + 'checks/cpu_neon_fp16.c')[0] +) +# FMA +NEON_VFPV4 = mod_features.new( + 'NEON_VFPV4', 202, implies: NEON_FP16, + test_code: files(source_root + 'checks/cpu_neon_vfpv4.c')[0] +) +# Advanced SIMD +ASIMD = mod_features.new( + 'ASIMD', 203, implies: NEON_VFPV4, detect: {'val': 'ASIMD', 'match': 'NEON.*'}, + test_code: files(source_root + 'checks/cpu_asimd.c')[0] +) +if cpu_family == 'aarch64' + # hardware baseline, they can't be enabled independently + NEON.update(implies: [NEON_FP16, NEON_VFPV4, ASIMD]) + NEON_FP16.update(implies: [NEON, NEON_VFPV4, ASIMD]) + NEON_VFPV4.update(implies: [NEON, NEON_FP16, ASIMD]) +elif cpu_family == 'arm' + NEON.update(args: '-mfpu=neon') + NEON_FP16.update(args: ['-mfp16-format=ieee', {'val': '-mfpu=neon-fp16', 'match': '-mfpu=.*'}]) + NEON_VFPV4.update(args: {'val': '-mfpu=neon-vfpv4', 'match': '-mfpu=.*'}) + ASIMD.update(args: [ + {'val': '-mfpu=neon-fp-armv8', 'match': '-mfpu=.*'}, + '-march=armv8-a+simd' + ]) +else + # should disable any prevalent features + NEON.update(disable: 'not supported by the current platform') +endif + diff --git a/unittests/featurestests.py b/unittests/featurestests.py new file mode 100644 index 000000000000..a863a9fb93cc --- /dev/null +++ b/unittests/featurestests.py @@ -0,0 +1,300 @@ +# Copyright (c) 2023, NumPy Developers. + +import re +import contextlib +from mesonbuild.interpreter import Interpreter +from mesonbuild.build import Build +from mesonbuild.mparser import FunctionNode, ArgumentNode, Token +from mesonbuild.modules import ModuleState +from mesonbuild.modules.features import Module +from mesonbuild.compilers import Compiler, CompileResult +from mesonbuild.mesonlib import MachineChoice +from mesonbuild.envconfig import MachineInfo + +from .baseplatformtests import BasePlatformTests +from run_tests import get_convincing_fake_env_and_cc + +class FakeCompiler(Compiler): + language = 'c' + + def __init__(self, trap_args = '', trap_code=''): + super().__init__( + ccache=[], exelist=[], version='0.0', + for_machine=MachineChoice.HOST, + info=MachineInfo( + system='linux', cpu_family='x86_64', + cpu='xeon', endian='little', + kernel='linux', subsystem='numpy' + ), + is_cross=True + ) + self.trap_args = trap_args + self.trap_code = trap_code + + def sanity_check(self, work_dir: str, environment: 'Environment') -> None: + pass + + def get_optimization_args(self, optimization_level: str) -> 'T.List[str]': + return [] + + def get_output_args(self, outputname: str) -> 'T.List[str]': + return [] + + def has_multi_arguments(self, args: 'T.List[str]', env: 'Environment') -> 'T.Tuple[bool, bool]': + if self.trap_args: + for a in args: + if re.match(self.trap_args, a): + return False, False + return True, False + + @contextlib.contextmanager + def compile(self, code: 'mesonlib.FileOrString', *args, **kwargs + ) -> 'T.Iterator[T.Optional[CompileResult]]': + if self.trap_code and re.match(self.trap_code, code): + rcode = -1 + else: + rcode = 0 + result = CompileResult(returncode=rcode) + yield result + + @contextlib.contextmanager + def cached_compile(self, code: 'mesonlib.FileOrString', *args, **kwargs + ) -> 'T.Iterator[T.Optional[CompileResult]]': + if self.trap_code and re.match(self.trap_code, code): + rcode = -1 + else: + rcode = 0 + result = CompileResult(returncode=rcode) + yield result + +class FeaturesTests(BasePlatformTests): + def setUp(self): + super().setUp() + env, cc = get_convincing_fake_env_and_cc( + bdir=self.builddir, prefix=self.prefix) + env.machines.target = env.machines.host + + build = Build(env) + interp = Interpreter(build, mock=True) + project = interp.funcs['project'] + filename = 'featurestests.py' + node = FunctionNode( + filename = filename, + lineno = 0, + colno = 0, + end_lineno = 0, + end_colno = 0, + func_name = 'FeaturesTests', + args = ArgumentNode(Token('string', filename, 0, 0, 0, None, '')) + ) + project(node, ['Test Module Features'], {'version': '0.1'}) + self.cc = cc + self.state = ModuleState(interp) + self.mod_features = Module() + + def clear_cache(self): + self.mod_features = Module() + + def mod_method(self, name: str, *args, **kwargs): + mth = self.mod_features.methods.get(name) + return mth(self.state, list(args), kwargs) + + def mod_new(self, *args, **kwargs): + return self.mod_method('new', *args, **kwargs) + + def mod_test(self, *args, **kwargs): + return self.mod_method('test', *args, **kwargs) + + def update_feature(self, feature, **kwargs): + feature.update_method(self.state, [], kwargs) + + def check_result(self, features, expected_result, anyfet=False, **kwargs): + is_supported, test_result = self.mod_test( + *features, compiler=FakeCompiler(**kwargs), + cached=False, anyfet=anyfet + ) + test_result = test_result.copy() # to avoid pop cached dict + test_result.pop('fail_reason') + self.assertEqual(is_supported, expected_result['is_supported']) + self.assertEqual(test_result, expected_result) + + def gen_basic_result(self, prevalent, predecessor=[]): + prevalent_names = [fet.name for fet in prevalent] + predecessor_names = [fet.name for fet in predecessor] + features_names = predecessor_names + prevalent_names + return { + 'target_name': '__'.join(prevalent_names), + 'prevalent_features': prevalent_names, + 'features': features_names, + 'args': [f'arg{i}' for i in range(1, len(features_names) + 1)], + 'detect': features_names, + 'defines': features_names, + 'undefines': [], + 'is_supported': True, + 'is_disabled': False + } + + def gen_fail_result(self, prevalent, is_supported=False, + is_disabled = False): + prevalent_names = [fet.name for fet in prevalent] + return { + 'target_name': '__'.join(prevalent_names), + 'prevalent_features': prevalent_names, + 'features': [], + 'args': [], + 'detect': [], + 'defines': [], + 'undefines': [], + 'is_supported': is_supported, + 'is_disabled': is_disabled + } + + def test_happy_path(self): + fet1 = self.mod_new('fet1', 1, args='arg1', test_code='test1') + fet2 = self.mod_new('fet2', 2, implies=fet1, args='arg2', test_code='test2') + fet3 = self.mod_new('fet3', 3, implies=fet2, args='arg3') + fet4 = self.mod_new('fet4', 4, implies=fet3, args='arg4', test_code='test4') + # fet5 doesn't imply fet4 so we can test target with muti prevalent features + fet5 = self.mod_new('fet5', 5, implies=fet3, args='arg5') + fet6 = self.mod_new('fet6', 6, implies=[fet4, fet5], args='arg6') + + # basic test expected the compiler support all operations + for test_features, prevalent, predecessor in [ + ([fet1], [fet1], []), + ([fet2], [fet2], [fet1]), + ([fet2, fet1], [fet2], [fet1]), + ([fet3], [fet3], [fet1, fet2]), + ([fet2, fet3, fet1], [fet3], [fet1, fet2]), + ([fet4, fet5], [fet4, fet5], [fet1, fet2, fet3]), + ([fet5, fet4], [fet4, fet5], [fet1, fet2, fet3]), + ([fet6], [fet6], [fet1, fet2, fet3, fet4, fet5]), + ]: + expected = self.gen_basic_result(prevalent, predecessor) + self.check_result(test_features, expected) + + for test_features, prevalent, trap_args in [ + ([fet1], [fet1], 'arg1'), + ([fet1], [fet1], 'arg1'), + ]: + expected = self.gen_fail_result(prevalent) + self.check_result(test_features, expected, trap_args=trap_args) + + def test_failures(self): + fet1 = self.mod_new('fet1', 1, args='arg1', test_code='test1') + fet2 = self.mod_new('fet2', 2, implies=fet1, args='arg2', test_code='test2') + fet3 = self.mod_new('fet3', 3, implies=fet2, args='arg3', test_code='test3') + fet4 = self.mod_new('fet4', 4, implies=fet3, args='arg4', test_code='test4') + # fet5 doesn't imply fet4 so we can test target with muti features + fet5 = self.mod_new('fet5', 5, implies=fet3, args='arg5', test_code='test5') + + for test_features, prevalent, disable, trap_args, trap_code in [ + # test by trap flags + ([fet1], [fet1], None, 'arg1', None), + ([fet2], [fet2], None, 'arg1', None), + ([fet2, fet1], [fet2], None, 'arg2', None), + ([fet3], [fet3], None, 'arg1', None), + ([fet3, fet2], [fet3], None, 'arg2', None), + ([fet3, fet1], [fet3], None, 'arg3', None), + ([fet3, fet1], [fet3], None, 'arg3', None), + ([fet5, fet4], [fet4, fet5], None, 'arg4', None), + ([fet5, fet4], [fet4, fet5], None, 'arg5', None), + # test by trap test_code + ([fet1], [fet1], None, None, 'test1'), + ([fet2], [fet2], None, None, 'test1'), + ([fet2, fet1], [fet2], None, None, 'test2'), + ([fet3], [fet3], None, None, 'test1'), + ([fet3, fet2], [fet3], None, None, 'test2'), + ([fet3, fet1], [fet3], None, None, 'test3'), + ([fet5, fet4], [fet4, fet5], None, None, 'test4'), + ([fet5, fet4], [fet4, fet5], None, None, 'test5'), + # test by disable feature + ([fet1], [fet1], fet1, None, None), + ([fet2], [fet2], fet1, None, None), + ([fet2, fet1], [fet2], fet2, None, None), + ([fet3], [fet3], fet1, None, None), + ([fet3, fet2], [fet3], fet2, None, None), + ([fet3, fet1], [fet3], fet3, None, None), + ([fet5, fet4], [fet4, fet5], fet4, None, None), + ([fet5, fet4], [fet4, fet5], fet5, None, None), + ]: + if disable: + self.update_feature(disable, disable='test disable') + expected = self.gen_fail_result(prevalent, is_disabled=not not disable) + self.check_result(test_features, expected, trap_args=trap_args, trap_code=trap_code) + + def test_any(self): + fet1 = self.mod_new('fet1', 1, args='arg1', test_code='test1') + fet2 = self.mod_new('fet2', 2, implies=fet1, args='arg2', test_code='test2') + fet3 = self.mod_new('fet3', 3, implies=fet2, args='arg3', test_code='test3') + fet4 = self.mod_new('fet4', 4, implies=fet3, args='arg4', test_code='test4') + # fet5 doesn't imply fet4 so we can test target with muti features + fet5 = self.mod_new('fet5', 5, implies=fet3, args='arg5', test_code='test5') + fet6 = self.mod_new('fet6', 6, implies=[fet4, fet5], args='arg6') + + for test_features, prevalent, predecessor, trap_args in [ + ([fet2], [fet1], [], 'arg2'), + ([fet6], [fet2], [fet1], 'arg3'), + ([fet6], [fet4], [fet1, fet2, fet3], 'arg5'), + ([fet5, fet4], [fet3], [fet1, fet2], 'arg4|arg5'), + ]: + expected = self.gen_basic_result(prevalent, predecessor) + self.check_result(test_features, expected, trap_args=trap_args, anyfet=True) + + def test_conflict_args(self): + fet1 = self.mod_new('fet1', 1, args='arg1', test_code='test1') + fet2 = self.mod_new('fet2', 2, implies=fet1, args='arg2', test_code='test2') + fet3 = self.mod_new('fet3', 3, implies=fet2, args='arg3') + fet4 = self.mod_new('fet4', 4, implies=fet3, args='arg4', test_code='test4') + fet5 = self.mod_new('fet5', 5, implies=fet3, args='arg5', test_code='test5') + fet6 = self.mod_new('fet6', 6, implies=[fet4, fet5], args='arch=xx') + + compiler = FakeCompiler() + for implies, attr, val, expected_vals in [ + ( + [fet3, fet4, fet5], + 'args', {'val':'arch=the_arch', 'match': 'arg.*'}, + ['arch=the_arch'], + ), + ( + [fet5, fet4], + 'args', {'val':'arch=', 'match': 'arg.*', 'mfilter': '[0-9]'}, + ['arch=12345'], + ), + ( + [fet5, fet4], + 'args', {'val':'arch=', 'match': 'arg.*', 'mfilter': '[0-9]', 'mjoin': '+'}, + ['arch=1+2+3+4+5'], + ), + ( + [fet5, fet4], + 'args', {'val':'arch=num*', 'match': 'arg.*[0-3]', 'mfilter': '[0-9]', 'mjoin': '*'}, + ['arg4', 'arg5', 'arch=num*1*2*3'], + ), + ( + [fet6], + 'args', {'val':'arch=', 'match': 'arg.*[0-9]|arch=.*', 'mfilter': '([0-9])|arch=(\w+)', 'mjoin': '*'}, + ['arch=1*2*3*4*5*xx'], + ), + ( + [fet3, fet4, fet5], + 'detect', {'val':'test_fet', 'match': 'fet.*[0-5]'}, + ['test_fet'], + ), + ( + [fet5, fet4], + 'detect', {'val':'fet', 'match': 'fet.*[0-5]', 'mfilter': '[0-9]'}, + ['fet12345'], + ), + ( + [fet5, fet4], + 'detect', {'val':'fet_', 'match': 'fet.*[0-5]', 'mfilter': '[0-9]', 'mjoin':'_'}, + ['fet_1_2_3_4_5'], + ), + ]: + test_fet = self.mod_new('test_fet', 7, implies=implies, **{attr:val}) + is_supported, test_result = self.mod_test( + test_fet, compiler=compiler, cached=False + ) + self.assertEqual(test_result['is_supported'], True) + self.assertEqual(test_result[attr], expected_vals) +