Debian Codegraph @

mesonbuild/interpreter/primitives/string.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2021 The Meson development team
3 from __future__ import annotations
4
5 import re
6 import os
7
8 import typing as T
9
10 from ... import mlog
11 from ...mesonlib import version_check_to_range, version_compare_many, underscorify
12 from ...interpreterbase import (
13 InterpreterObject,
14 MesonOperator,
15 ObjectHolder,
16 FeatureNew,
17 typed_operator,
18 noArgsFlattening,
19 noKwargs,
20 noPosargs,
21 typed_pos_args,
22 InvalidArguments,
23 FeatureBroken,
24 stringifyUserArguments,
25 )
26
27
28 if T.TYPE_CHECKING:
29 from ...interpreterbase import TYPE_var, TYPE_kwargs
30
31 class StringHolder(ObjectHolder[str]):
32 TRIVIAL_OPERATORS = {
33 # Arithmetic
34 MesonOperator.PLUS: (str, lambda obj, x: obj.held_object + x),
35
36 # Comparison
37 MesonOperator.EQUALS: (str, lambda obj, x: obj.held_object == x),
38 MesonOperator.NOT_EQUALS: (str, lambda obj, x: obj.held_object != x),
39 MesonOperator.GREATER: (str, lambda obj, x: obj.held_object > x),
40 MesonOperator.LESS: (str, lambda obj, x: obj.held_object < x),
41 MesonOperator.GREATER_EQUALS: (str, lambda obj, x: obj.held_object >= x),
42 MesonOperator.LESS_EQUALS: (str, lambda obj, x: obj.held_object <= x),
43 }
44
45 def display_name(self) -> str:
46 return 'str'
47
48 @noKwargs
49 @typed_pos_args('str.contains', str)
50 @InterpreterObject.method('contains')
51 def contains_method(self, args: T.Tuple[str], kwargs: TYPE_kwargs) -> bool:
52 return self.held_object.find(args[0]) >= 0
53
54 @noKwargs
55 @typed_pos_args('str.startswith', str)
56 @InterpreterObject.method('startswith')
57 def startswith_method(self, args: T.Tuple[str], kwargs: TYPE_kwargs) -> bool:
58 return self.held_object.startswith(args[0])
59
60 @noKwargs
61 @typed_pos_args('str.endswith', str)
62 @InterpreterObject.method('endswith')
63 def endswith_method(self, args: T.Tuple[str], kwargs: TYPE_kwargs) -> bool:
64 return self.held_object.endswith(args[0])
65
66 @noArgsFlattening
67 @noKwargs
68 @typed_pos_args('str.format', varargs=object)
69 @InterpreterObject.method('format')
70 def format_method(self, args: T.Tuple[T.List[TYPE_var]], kwargs: TYPE_kwargs) -> str:
71 arg_strings: T.List[str] = []
72 for arg in args[0]:
73 try:
74 arg_strings.append(stringifyUserArguments(arg, self.subproject))
75 except InvalidArguments as e:
76 FeatureBroken.single_use(f'str.format: {str(e)}', '1.3.0', self.subproject, location=self.current_node)
77 arg_strings.append(str(arg))
78
79 def arg_replace(match: T.Match[str]) -> str:
80 idx = int(match.group(1))
81 if idx >= len(arg_strings):
82 raise InvalidArguments(f'Format placeholder @{idx}@ out of range.')
83 return arg_strings[idx]
84
85 return re.sub(r'@(\d+)@', arg_replace, self.held_object)
86
87 @noKwargs
88 @noPosargs
89 @FeatureNew('str.splitlines', '1.2.0')
90 @InterpreterObject.method('splitlines')
91 def splitlines_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> T.List[str]:
92 return self.held_object.splitlines()
93
94 @noKwargs
95 @typed_pos_args('str.join', varargs=str)
96 @InterpreterObject.method('join')
97 def join_method(self, args: T.Tuple[T.List[str]], kwargs: TYPE_kwargs) -> str:
98 return self.held_object.join(args[0])
99
100 @noKwargs
101 @FeatureNew('str.replace', '0.58.0')
102 @typed_pos_args('str.replace', str, str)
103 @InterpreterObject.method('replace')
104 def replace_method(self, args: T.Tuple[str, str], kwargs: TYPE_kwargs) -> str:
105 return self.held_object.replace(args[0], args[1])
106
107 @noKwargs
108 @typed_pos_args('str.split', optargs=[str])
109 @InterpreterObject.method('split')
110 def split_method(self, args: T.Tuple[T.Optional[str]], kwargs: TYPE_kwargs) -> T.List[str]:
111 delimiter = args[0]
112 if delimiter == '':
113 raise InvalidArguments('str.split() delimitier must not be an empty string')
114 return self.held_object.split(delimiter)
115
116 @noKwargs
117 @typed_pos_args('str.strip', optargs=[str])
118 @InterpreterObject.method('strip')
119 def strip_method(self, args: T.Tuple[T.Optional[str]], kwargs: TYPE_kwargs) -> str:
120 if args[0]:
121 FeatureNew.single_use('str.strip with a positional argument', '0.43.0', self.subproject, location=self.current_node)
122 return self.held_object.strip(args[0])
123
124 @noKwargs
125 @FeatureNew('str.substring', '0.56.0')
126 @typed_pos_args('str.substring', optargs=[int, int])
127 @InterpreterObject.method('substring')
128 def substring_method(self, args: T.Tuple[T.Optional[int], T.Optional[int]], kwargs: TYPE_kwargs) -> str:
129 start = args[0] if args[0] is not None else 0
130 end = args[1] if args[1] is not None else len(self.held_object)
131 return self.held_object[start:end]
132
133 @noKwargs
134 @noPosargs
135 @InterpreterObject.method('to_int')
136 def to_int_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> int:
137 try:
138 s = self.held_object.strip()
139 try:
140 # For backward compatibility, try to parse the string as a decimal
141 # integer first. This is to allow leading zeros which are disallowed
142 # when determining the integer base from the string prefix.
143 return int(s)
144 except ValueError:
145 return int(s, base=0)
146 except ValueError:
147 raise InvalidArguments(f'String {self.held_object!r} cannot be converted to int')
148
149 @noKwargs
150 @noPosargs
151 @InterpreterObject.method('to_lower')
152 def to_lower_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
153 return self.held_object.lower()
154
155 @noKwargs
156 @noPosargs
157 @InterpreterObject.method('to_upper')
158 def to_upper_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
159 return self.held_object.upper()
160
161 @noKwargs
162 @noPosargs
163 @InterpreterObject.method('underscorify')
164 def underscorify_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str:
165 return underscorify(self.held_object)
166
167 @noKwargs
168 @InterpreterObject.method('version_compare')
169 @typed_pos_args('str.version_compare', varargs=str, min_varargs=1)
170 def version_compare_method(self, args: T.Tuple[T.List[str]], kwargs: TYPE_kwargs) -> bool:
171 if len(args[0]) > 1:
172 FeatureNew.single_use('version_compare() with multiple arguments', '1.8.0', self.subproject, location=self.current_node)
173 return version_compare_many(self.held_object, args[0])[0]
174
175 @staticmethod
176 def _op_div(this: str, other: str) -> str:
177 return os.path.join(this, other).replace('\\', '/')
178
179 @FeatureNew('/ with string arguments', '0.49.0')
180 @typed_operator(MesonOperator.DIV, str)
181 @InterpreterObject.operator(MesonOperator.DIV)
182 def op_div(self, other: str) -> str:
183 return self._op_div(self.held_object, other)
184
185 @typed_operator(MesonOperator.INDEX, int)
186 @InterpreterObject.operator(MesonOperator.INDEX)
187 def op_index(self, other: int) -> str:
188 try:
189 return self.held_object[other]
190 except IndexError:
191 raise InvalidArguments(f'Index {other} out of bounds of string of size {len(self.held_object)}.')
192
193 @FeatureNew('"in" string operator', '1.0.0')
194 @typed_operator(MesonOperator.IN, str)
195 @InterpreterObject.operator(MesonOperator.IN)
196 def op_in(self, other: str) -> bool:
197 return other in self.held_object
198
199 @FeatureNew('"not in" string operator', '1.0.0')
200 @typed_operator(MesonOperator.NOT_IN, str)
201 @InterpreterObject.operator(MesonOperator.NOT_IN)
202 def op_notin(self, other: str) -> bool:
203 return other not in self.held_object
204
205
206 class MesonVersionString(str):
207 pass
208
209 class MesonVersionStringHolder(StringHolder):
210 @noKwargs
211 @InterpreterObject.method('version_compare')
212 @typed_pos_args('str.version_compare', varargs=str, min_varargs=1)
213 def version_compare_method(self, args: T.Tuple[T.List[str]], kwargs: TYPE_kwargs) -> bool:
214 unsupported = False
215 for constraint in args[0]:
216 if constraint.strip().startswith('!'):
217 unsupported = True
218 break
219 if len(args[0]) > 1:
220 FeatureNew.single_use('meson.version().version_compare() with multiple arguments', '1.10.0',
221 self.subproject, 'From 1.8.0 - 1.9.* it failed to match str.version_compare',
222 location=self.current_node)
223 if unsupported:
224 mlog.debug('meson.version().version_compare() with != constraints',
225 'does not support overriding minimum meson_version checks.')
226 else:
227 self.interpreter.tmp_meson_version = version_check_to_range(args[0])
228
229 return version_compare_many(self.held_object, args[0])[0]
230
231
232 # These special subclasses of string exist to cover the case where a dependency
233 # exports a string variable interchangeable with a system dependency. This
234 # matters because a dependency can only have string-type get_variable() return
235 # values. If at any time dependencies start supporting additional variable
236 # types, this class could be deprecated.
237 class DependencyVariableString(str):
238 pass
239
240 class DependencyVariableStringHolder(StringHolder):
241 @InterpreterObject.operator(MesonOperator.DIV)
242 def op_div(self, other: str) -> T.Union[str, DependencyVariableString]:
243 ret = super().op_div(other)
244 if '..' in other:
245 return ret
246 return DependencyVariableString(ret)
247
248
249 class OptionString(str):
250 optname: str
251
252 def __new__(cls, value: str, name: str) -> 'OptionString':
253 obj = str.__new__(cls, value)
254 obj.optname = name
255 return obj
256
257 def __getnewargs__(self) -> T.Tuple[str, str]: # type: ignore # because the entire point of this is to diverge
258 return (str(self), self.optname)
259
260
261 class OptionStringHolder(StringHolder):
262 held_object: OptionString
263
264 @InterpreterObject.operator(MesonOperator.DIV)
265 def op_div(self, other: str) -> T.Union[str, OptionString]:
266 ret = super().op_div(other)
267 name = self._op_div(self.held_object.optname, other)
268 return OptionString(ret, name)