| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2013-2014 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import re |
| 7 |
import typing as T |
| 8 |
|
| 9 |
from . import options |
| 10 |
from . import mesonlib |
| 11 |
from .options import OptionKey |
| 12 |
from . import mparser |
| 13 |
from . import mlog |
| 14 |
from .interpreterbase import FeatureNew, FeatureDeprecated, typed_pos_args, typed_kwargs, ContainerTypeInfo, KwargInfo |
| 15 |
from .interpreter.type_checking import NoneType, in_set_validator |
| 16 |
|
| 17 |
if T.TYPE_CHECKING: |
| 18 |
from .interpreterbase import TYPE_var, TYPE_kwargs |
| 19 |
from .mesonlib import SubProject |
| 20 |
from typing_extensions import TypedDict, Literal |
| 21 |
from .options import OptionStore |
| 22 |
|
| 23 |
_DEPRECATED_ARGS = T.Union[bool, str, T.Dict[str, str], T.List[str]] |
| 24 |
|
| 25 |
FuncOptionArgs = TypedDict('FuncOptionArgs', { |
| 26 |
'type': str, |
| 27 |
'description': str, |
| 28 |
'yield': bool, |
| 29 |
'choices': T.Optional[T.List[str]], |
| 30 |
'value': object, |
| 31 |
'min': T.Optional[int], |
| 32 |
'max': T.Optional[int], |
| 33 |
'deprecated': _DEPRECATED_ARGS, |
| 34 |
}) |
| 35 |
|
| 36 |
class StringArgs(TypedDict): |
| 37 |
value: str |
| 38 |
|
| 39 |
class BooleanArgs(TypedDict): |
| 40 |
value: bool |
| 41 |
|
| 42 |
class ComboArgs(TypedDict): |
| 43 |
value: str |
| 44 |
choices: T.List[str] |
| 45 |
|
| 46 |
class IntegerArgs(TypedDict): |
| 47 |
value: int |
| 48 |
min: T.Optional[int] |
| 49 |
max: T.Optional[int] |
| 50 |
|
| 51 |
class StringArrayArgs(TypedDict): |
| 52 |
value: T.Optional[T.Union[str, T.List[str]]] |
| 53 |
choices: T.List[str] |
| 54 |
|
| 55 |
class FeatureArgs(TypedDict): |
| 56 |
value: Literal['enabled', 'disabled', 'auto'] |
| 57 |
choices: T.List[str] |
| 58 |
|
| 59 |
|
| 60 |
class OptionException(mesonlib.MesonException): |
| 61 |
pass |
| 62 |
|
| 63 |
|
| 64 |
optname_regex = re.compile('[^a-zA-Z0-9_-]') |
| 65 |
|
| 66 |
|
| 67 |
class OptionInterpreter: |
| 68 |
def __init__(self, optionstore: 'OptionStore', subproject: 'SubProject') -> None: |
| 69 |
self.options: options.MutableKeyedOptionDictType = {} |
| 70 |
self.subproject = subproject |
| 71 |
self.option_types: T.Dict[str, T.Callable[..., options.AnyOptionType]] = { |
| 72 |
'string': self.string_parser, |
| 73 |
'boolean': self.boolean_parser, |
| 74 |
'combo': self.combo_parser, |
| 75 |
'integer': self.integer_parser, |
| 76 |
'array': self.string_array_parser, |
| 77 |
'feature': self.feature_parser, |
| 78 |
} |
| 79 |
self.optionstore = optionstore |
| 80 |
|
| 81 |
def process(self, option_file: str) -> None: |
| 82 |
try: |
| 83 |
with open(option_file, encoding='utf-8') as f: |
| 84 |
code = f.read() |
| 85 |
except UnicodeDecodeError as e: |
| 86 |
raise mesonlib.MesonException(f'Malformed option file {option_file!r} failed to parse as unicode: {e}') |
| 87 |
try: |
| 88 |
ast = mparser.Parser(code, option_file).parse() |
| 89 |
except mesonlib.MesonException as me: |
| 90 |
me.file = option_file |
| 91 |
raise me |
| 92 |
if not isinstance(ast, mparser.CodeBlockNode): |
| 93 |
e = OptionException('Option file is malformed.') |
| 94 |
e.lineno = ast.lineno() |
| 95 |
e.file = option_file |
| 96 |
raise e |
| 97 |
for cur in ast.lines: |
| 98 |
try: |
| 99 |
self.current_node = cur |
| 100 |
self.evaluate_statement(cur) |
| 101 |
except mesonlib.MesonException as e: |
| 102 |
e.lineno = cur.lineno |
| 103 |
e.colno = cur.colno |
| 104 |
e.file = option_file |
| 105 |
raise e |
| 106 |
except Exception as e: |
| 107 |
raise mesonlib.MesonException( |
| 108 |
str(e), lineno=cur.lineno, colno=cur.colno, file=option_file) |
| 109 |
|
| 110 |
def reduce_single(self, arg: T.Union[str, mparser.BaseNode]) -> 'TYPE_var': |
| 111 |
if isinstance(arg, str): |
| 112 |
return arg |
| 113 |
if isinstance(arg, mparser.ParenthesizedNode): |
| 114 |
return self.reduce_single(arg.inner) |
| 115 |
elif isinstance(arg, (mparser.StringNode, mparser.BooleanNode, mparser.NumberNode)): |
| 116 |
return arg.value |
| 117 |
elif isinstance(arg, mparser.ArrayNode): |
| 118 |
return [self.reduce_single(curarg) for curarg in arg.args.arguments] |
| 119 |
elif isinstance(arg, mparser.DictNode): |
| 120 |
d = {} |
| 121 |
for k, v in arg.args.kwargs.items(): |
| 122 |
if not isinstance(k, mparser.StringNode): |
| 123 |
raise OptionException('Dictionary keys must be a string literal') |
| 124 |
d[k.value] = self.reduce_single(v) |
| 125 |
return d |
| 126 |
elif isinstance(arg, mparser.UMinusNode): |
| 127 |
res = self.reduce_single(arg.value) |
| 128 |
if not isinstance(res, (int, float)): |
| 129 |
raise OptionException('Token after "-" is not a number') |
| 130 |
FeatureNew.single_use('negative numbers in meson_options.txt', '0.54.1', self.subproject) |
| 131 |
return -res |
| 132 |
elif isinstance(arg, mparser.NotNode): |
| 133 |
res = self.reduce_single(arg.value) |
| 134 |
if not isinstance(res, bool): |
| 135 |
raise OptionException('Token after "not" is not a a boolean') |
| 136 |
FeatureNew.single_use('negation ("not") in meson_options.txt', '0.54.1', self.subproject) |
| 137 |
return not res |
| 138 |
elif isinstance(arg, mparser.ArithmeticNode): |
| 139 |
l = self.reduce_single(arg.left) |
| 140 |
r = self.reduce_single(arg.right) |
| 141 |
if not (arg.operation == '+' and isinstance(l, str) and isinstance(r, str)): |
| 142 |
raise OptionException('Only string concatenation with the "+" operator is allowed') |
| 143 |
FeatureNew.single_use('string concatenation in meson_options.txt', '0.55.0', self.subproject) |
| 144 |
return l + r |
| 145 |
else: |
| 146 |
raise OptionException('Arguments may only be string, int, bool, or array of those.') |
| 147 |
|
| 148 |
def reduce_arguments(self, args: mparser.ArgumentNode) -> T.Tuple['TYPE_var', 'TYPE_kwargs']: |
| 149 |
if args.incorrect_order(): |
| 150 |
raise OptionException('All keyword arguments must be after positional arguments.') |
| 151 |
reduced_pos = [self.reduce_single(arg) for arg in args.arguments] |
| 152 |
reduced_kw = {} |
| 153 |
for key in args.kwargs.keys(): |
| 154 |
if not isinstance(key, mparser.IdNode): |
| 155 |
raise OptionException('Keyword argument name is not a string.') |
| 156 |
a = args.kwargs[key] |
| 157 |
reduced_kw[key.value] = self.reduce_single(a) |
| 158 |
return reduced_pos, reduced_kw |
| 159 |
|
| 160 |
def evaluate_statement(self, node: mparser.BaseNode) -> None: |
| 161 |
if not isinstance(node, mparser.FunctionNode): |
| 162 |
raise OptionException('Option file may only contain option definitions') |
| 163 |
func_name = node.func_name.value |
| 164 |
if func_name != 'option': |
| 165 |
raise OptionException('Only calls to option() are allowed in option files.') |
| 166 |
(posargs, kwargs) = self.reduce_arguments(node.args) |
| 167 |
self.func_option(posargs, kwargs) |
| 168 |
|
| 169 |
@typed_kwargs( |
| 170 |
'option', |
| 171 |
KwargInfo( |
| 172 |
'type', |
| 173 |
str, |
| 174 |
required=True, |
| 175 |
validator=in_set_validator({'string', 'boolean', 'integer', 'combo', 'array', 'feature'}) |
| 176 |
), |
| 177 |
KwargInfo('description', str, default=''), |
| 178 |
KwargInfo( |
| 179 |
'deprecated', |
| 180 |
(bool, str, ContainerTypeInfo(dict, str), ContainerTypeInfo(list, str)), |
| 181 |
default=False, |
| 182 |
since='0.60.0', |
| 183 |
since_values={str: '0.63.0'}, |
| 184 |
), |
| 185 |
KwargInfo('yield', bool, default=options.DEFAULT_YIELDING, since='0.45.0'), |
| 186 |
allow_unknown=True, |
| 187 |
) |
| 188 |
@typed_pos_args('option', str) |
| 189 |
def func_option(self, args: T.Tuple[str], kwargs: 'FuncOptionArgs') -> None: |
| 190 |
opt_name = args[0] |
| 191 |
if optname_regex.search(opt_name) is not None: |
| 192 |
raise OptionException('Option names can only contain letters, numbers or dashes.') |
| 193 |
key = OptionKey.from_string(opt_name).evolve(subproject=self.subproject) |
| 194 |
if self.optionstore.is_reserved_name(key): |
| 195 |
raise OptionException('Option name %s is reserved.' % opt_name) |
| 196 |
|
| 197 |
opt_type = kwargs['type'] |
| 198 |
parser = self.option_types[opt_type] |
| 199 |
description = kwargs['description'] or opt_name |
| 200 |
|
| 201 |
# Drop the arguments we've already consumed |
| 202 |
n_kwargs = {k: v for k, v in kwargs.items() |
| 203 |
if k not in {'type', 'description', 'deprecated', 'yield'}} |
| 204 |
|
| 205 |
opt = parser(opt_name, description, (kwargs['yield'], kwargs['deprecated']), n_kwargs) |
| 206 |
if key in self.options: |
| 207 |
mlog.deprecation(f'Option {opt_name} already exists.') |
| 208 |
self.options[key] = opt |
| 209 |
|
| 210 |
@typed_kwargs( |
| 211 |
'string option', |
| 212 |
KwargInfo('value', str, default=''), |
| 213 |
) |
| 214 |
def string_parser(self, name: str, description: str, args: T.Tuple[bool, _DEPRECATED_ARGS], kwargs: StringArgs) -> options.UserOption: |
| 215 |
return options.UserStringOption(name, description, kwargs['value'], *args) |
| 216 |
|
| 217 |
@typed_kwargs( |
| 218 |
'boolean option', |
| 219 |
KwargInfo( |
| 220 |
'value', |
| 221 |
(bool, str), |
| 222 |
default=True, |
| 223 |
validator=lambda x: None if isinstance(x, bool) or x in {'true', 'false'} else 'boolean options must have boolean values', |
| 224 |
deprecated_values={str: ('1.1.0', 'use a boolean, not a string')}, |
| 225 |
), |
| 226 |
) |
| 227 |
def boolean_parser(self, name: str, description: str, args: T.Tuple[bool, _DEPRECATED_ARGS], kwargs: BooleanArgs) -> options.UserOption: |
| 228 |
yielding, deprecated = args |
| 229 |
return options.UserBooleanOption(name, description, kwargs['value'], yielding=yielding, deprecated=deprecated) |
| 230 |
|
| 231 |
@typed_kwargs( |
| 232 |
'combo option', |
| 233 |
KwargInfo('value', (str, NoneType)), |
| 234 |
KwargInfo('choices', ContainerTypeInfo(list, str, allow_empty=False), required=True), |
| 235 |
) |
| 236 |
def combo_parser(self, name: str, description: str, args: T.Tuple[bool, _DEPRECATED_ARGS], kwargs: ComboArgs) -> options.UserOption: |
| 237 |
choices = kwargs['choices'] |
| 238 |
value = kwargs['value'] |
| 239 |
if value is None: |
| 240 |
value = kwargs['choices'][0] |
| 241 |
return options.UserComboOption(name, description, value, *args, choices=choices) |
| 242 |
|
| 243 |
@typed_kwargs( |
| 244 |
'integer option', |
| 245 |
KwargInfo( |
| 246 |
'value', |
| 247 |
(int, str), |
| 248 |
default=True, |
| 249 |
deprecated_values={str: ('1.1.0', 'use an integer, not a string')}, |
| 250 |
convertor=int, |
| 251 |
), |
| 252 |
KwargInfo('min', (int, NoneType)), |
| 253 |
KwargInfo('max', (int, NoneType)), |
| 254 |
) |
| 255 |
def integer_parser(self, name: str, description: str, args: T.Tuple[bool, _DEPRECATED_ARGS], kwargs: IntegerArgs) -> options.UserOption: |
| 256 |
return options.UserIntegerOption( |
| 257 |
name, description, kwargs['value'], *args, min_value=kwargs['min'], max_value=kwargs['max']) |
| 258 |
|
| 259 |
@typed_kwargs( |
| 260 |
'string array option', |
| 261 |
KwargInfo('value', (ContainerTypeInfo(list, str), str, NoneType)), |
| 262 |
KwargInfo('choices', ContainerTypeInfo(list, str), default=[]), |
| 263 |
) |
| 264 |
def string_array_parser(self, name: str, description: str, args: T.Tuple[bool, _DEPRECATED_ARGS], kwargs: StringArrayArgs) -> options.UserOption: |
| 265 |
choices = kwargs['choices'] |
| 266 |
value = kwargs['value'] if kwargs['value'] is not None else choices |
| 267 |
if isinstance(value, str): |
| 268 |
if value.startswith('['): |
| 269 |
FeatureDeprecated('String value for array option', '1.3.0').use(self.subproject) |
| 270 |
else: |
| 271 |
raise mesonlib.MesonException('Value does not define an array: ' + value) |
| 272 |
return options.UserStringArrayOption( |
| 273 |
name, description, value, |
| 274 |
choices=choices, |
| 275 |
yielding=args[0], |
| 276 |
deprecated=args[1]) |
| 277 |
|
| 278 |
@typed_kwargs( |
| 279 |
'feature option', |
| 280 |
KwargInfo('value', str, default='auto', validator=in_set_validator({'auto', 'enabled', 'disabled'})), |
| 281 |
) |
| 282 |
def feature_parser(self, name: str, description: str, args: T.Tuple[bool, _DEPRECATED_ARGS], kwargs: FeatureArgs) -> options.UserOption: |
| 283 |
return options.UserFeatureOption(name, description, kwargs['value'], *args) |