ZTWHHH commited on
Commit
4d4e9e0
·
verified ·
1 Parent(s): 371872c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. vllm/lib/python3.10/site-packages/attr/__init__.py +104 -0
  2. vllm/lib/python3.10/site-packages/attr/__init__.pyi +389 -0
  3. vllm/lib/python3.10/site-packages/attr/__pycache__/__init__.cpython-310.pyc +0 -0
  4. vllm/lib/python3.10/site-packages/attr/__pycache__/_cmp.cpython-310.pyc +0 -0
  5. vllm/lib/python3.10/site-packages/attr/__pycache__/_compat.cpython-310.pyc +0 -0
  6. vllm/lib/python3.10/site-packages/attr/__pycache__/_config.cpython-310.pyc +0 -0
  7. vllm/lib/python3.10/site-packages/attr/__pycache__/_funcs.cpython-310.pyc +0 -0
  8. vllm/lib/python3.10/site-packages/attr/__pycache__/_make.cpython-310.pyc +0 -0
  9. vllm/lib/python3.10/site-packages/attr/__pycache__/_next_gen.cpython-310.pyc +0 -0
  10. vllm/lib/python3.10/site-packages/attr/__pycache__/_version_info.cpython-310.pyc +0 -0
  11. vllm/lib/python3.10/site-packages/attr/__pycache__/converters.cpython-310.pyc +0 -0
  12. vllm/lib/python3.10/site-packages/attr/__pycache__/exceptions.cpython-310.pyc +0 -0
  13. vllm/lib/python3.10/site-packages/attr/__pycache__/filters.cpython-310.pyc +0 -0
  14. vllm/lib/python3.10/site-packages/attr/__pycache__/setters.cpython-310.pyc +0 -0
  15. vllm/lib/python3.10/site-packages/attr/__pycache__/validators.cpython-310.pyc +0 -0
  16. vllm/lib/python3.10/site-packages/attr/_cmp.py +160 -0
  17. vllm/lib/python3.10/site-packages/attr/_cmp.pyi +13 -0
  18. vllm/lib/python3.10/site-packages/attr/_compat.py +94 -0
  19. vllm/lib/python3.10/site-packages/attr/_config.py +31 -0
  20. vllm/lib/python3.10/site-packages/attr/_funcs.py +468 -0
  21. vllm/lib/python3.10/site-packages/attr/_make.py +3055 -0
  22. vllm/lib/python3.10/site-packages/attr/_next_gen.py +623 -0
  23. vllm/lib/python3.10/site-packages/attr/_typing_compat.pyi +15 -0
  24. vllm/lib/python3.10/site-packages/attr/_version_info.py +86 -0
  25. vllm/lib/python3.10/site-packages/attr/_version_info.pyi +9 -0
  26. vllm/lib/python3.10/site-packages/attr/converters.py +162 -0
  27. vllm/lib/python3.10/site-packages/attr/converters.pyi +19 -0
  28. vllm/lib/python3.10/site-packages/attr/exceptions.py +95 -0
  29. vllm/lib/python3.10/site-packages/attr/exceptions.pyi +17 -0
  30. vllm/lib/python3.10/site-packages/attr/filters.py +72 -0
  31. vllm/lib/python3.10/site-packages/attr/filters.pyi +6 -0
  32. vllm/lib/python3.10/site-packages/attr/py.typed +0 -0
  33. vllm/lib/python3.10/site-packages/attr/setters.py +79 -0
  34. vllm/lib/python3.10/site-packages/attr/setters.pyi +20 -0
  35. vllm/lib/python3.10/site-packages/attr/validators.py +710 -0
  36. vllm/lib/python3.10/site-packages/attr/validators.pyi +86 -0
  37. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/acero/api.h +32 -0
  38. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/acero/hash_join_dict.h +318 -0
  39. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/acero/map_node.h +81 -0
  40. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/acero/order_by_impl.h +56 -0
  41. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/acero/query_context.h +151 -0
  42. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/acero/task_util.h +102 -0
  43. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_primitive.h +210 -0
  44. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/c/abi.h +233 -0
  45. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/c/bridge.h +409 -0
  46. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/c/dlpack_abi.h +321 -0
  47. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/c/helpers.h +178 -0
  48. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/compute/api_aggregate.h +466 -0
  49. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/compute/api_scalar.h +1722 -0
  50. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/compute/expression.h +295 -0
vllm/lib/python3.10/site-packages/attr/__init__.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ """
4
+ Classes Without Boilerplate
5
+ """
6
+
7
+ from functools import partial
8
+ from typing import Callable, Literal, Protocol
9
+
10
+ from . import converters, exceptions, filters, setters, validators
11
+ from ._cmp import cmp_using
12
+ from ._config import get_run_validators, set_run_validators
13
+ from ._funcs import asdict, assoc, astuple, has, resolve_types
14
+ from ._make import (
15
+ NOTHING,
16
+ Attribute,
17
+ Converter,
18
+ Factory,
19
+ _Nothing,
20
+ attrib,
21
+ attrs,
22
+ evolve,
23
+ fields,
24
+ fields_dict,
25
+ make_class,
26
+ validate,
27
+ )
28
+ from ._next_gen import define, field, frozen, mutable
29
+ from ._version_info import VersionInfo
30
+
31
+
32
+ s = attributes = attrs
33
+ ib = attr = attrib
34
+ dataclass = partial(attrs, auto_attribs=True) # happy Easter ;)
35
+
36
+
37
+ class AttrsInstance(Protocol):
38
+ pass
39
+
40
+
41
+ NothingType = Literal[_Nothing.NOTHING]
42
+
43
+ __all__ = [
44
+ "NOTHING",
45
+ "Attribute",
46
+ "AttrsInstance",
47
+ "Converter",
48
+ "Factory",
49
+ "NothingType",
50
+ "asdict",
51
+ "assoc",
52
+ "astuple",
53
+ "attr",
54
+ "attrib",
55
+ "attributes",
56
+ "attrs",
57
+ "cmp_using",
58
+ "converters",
59
+ "define",
60
+ "evolve",
61
+ "exceptions",
62
+ "field",
63
+ "fields",
64
+ "fields_dict",
65
+ "filters",
66
+ "frozen",
67
+ "get_run_validators",
68
+ "has",
69
+ "ib",
70
+ "make_class",
71
+ "mutable",
72
+ "resolve_types",
73
+ "s",
74
+ "set_run_validators",
75
+ "setters",
76
+ "validate",
77
+ "validators",
78
+ ]
79
+
80
+
81
+ def _make_getattr(mod_name: str) -> Callable:
82
+ """
83
+ Create a metadata proxy for packaging information that uses *mod_name* in
84
+ its warnings and errors.
85
+ """
86
+
87
+ def __getattr__(name: str) -> str:
88
+ if name not in ("__version__", "__version_info__"):
89
+ msg = f"module {mod_name} has no attribute {name}"
90
+ raise AttributeError(msg)
91
+
92
+ from importlib.metadata import metadata
93
+
94
+ meta = metadata("attrs")
95
+
96
+ if name == "__version_info__":
97
+ return VersionInfo._from_version_string(meta["version"])
98
+
99
+ return meta["version"]
100
+
101
+ return __getattr__
102
+
103
+
104
+ __getattr__ = _make_getattr(__name__)
vllm/lib/python3.10/site-packages/attr/__init__.pyi ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ import sys
3
+
4
+ from typing import (
5
+ Any,
6
+ Callable,
7
+ Generic,
8
+ Literal,
9
+ Mapping,
10
+ Protocol,
11
+ Sequence,
12
+ TypeVar,
13
+ overload,
14
+ )
15
+
16
+ # `import X as X` is required to make these public
17
+ from . import converters as converters
18
+ from . import exceptions as exceptions
19
+ from . import filters as filters
20
+ from . import setters as setters
21
+ from . import validators as validators
22
+ from ._cmp import cmp_using as cmp_using
23
+ from ._typing_compat import AttrsInstance_
24
+ from ._version_info import VersionInfo
25
+ from attrs import (
26
+ define as define,
27
+ field as field,
28
+ mutable as mutable,
29
+ frozen as frozen,
30
+ _EqOrderType,
31
+ _ValidatorType,
32
+ _ConverterType,
33
+ _ReprArgType,
34
+ _OnSetAttrType,
35
+ _OnSetAttrArgType,
36
+ _FieldTransformer,
37
+ _ValidatorArgType,
38
+ )
39
+
40
+ if sys.version_info >= (3, 10):
41
+ from typing import TypeGuard, TypeAlias
42
+ else:
43
+ from typing_extensions import TypeGuard, TypeAlias
44
+
45
+ if sys.version_info >= (3, 11):
46
+ from typing import dataclass_transform
47
+ else:
48
+ from typing_extensions import dataclass_transform
49
+
50
+ __version__: str
51
+ __version_info__: VersionInfo
52
+ __title__: str
53
+ __description__: str
54
+ __url__: str
55
+ __uri__: str
56
+ __author__: str
57
+ __email__: str
58
+ __license__: str
59
+ __copyright__: str
60
+
61
+ _T = TypeVar("_T")
62
+ _C = TypeVar("_C", bound=type)
63
+
64
+ _FilterType = Callable[["Attribute[_T]", _T], bool]
65
+
66
+ # We subclass this here to keep the protocol's qualified name clean.
67
+ class AttrsInstance(AttrsInstance_, Protocol):
68
+ pass
69
+
70
+ _A = TypeVar("_A", bound=type[AttrsInstance])
71
+
72
+ class _Nothing(enum.Enum):
73
+ NOTHING = enum.auto()
74
+
75
+ NOTHING = _Nothing.NOTHING
76
+ NothingType: TypeAlias = Literal[_Nothing.NOTHING]
77
+
78
+ # NOTE: Factory lies about its return type to make this possible:
79
+ # `x: List[int] # = Factory(list)`
80
+ # Work around mypy issue #4554 in the common case by using an overload.
81
+
82
+ @overload
83
+ def Factory(factory: Callable[[], _T]) -> _T: ...
84
+ @overload
85
+ def Factory(
86
+ factory: Callable[[Any], _T],
87
+ takes_self: Literal[True],
88
+ ) -> _T: ...
89
+ @overload
90
+ def Factory(
91
+ factory: Callable[[], _T],
92
+ takes_self: Literal[False],
93
+ ) -> _T: ...
94
+
95
+ In = TypeVar("In")
96
+ Out = TypeVar("Out")
97
+
98
+ class Converter(Generic[In, Out]):
99
+ @overload
100
+ def __init__(self, converter: Callable[[In], Out]) -> None: ...
101
+ @overload
102
+ def __init__(
103
+ self,
104
+ converter: Callable[[In, AttrsInstance, Attribute], Out],
105
+ *,
106
+ takes_self: Literal[True],
107
+ takes_field: Literal[True],
108
+ ) -> None: ...
109
+ @overload
110
+ def __init__(
111
+ self,
112
+ converter: Callable[[In, Attribute], Out],
113
+ *,
114
+ takes_field: Literal[True],
115
+ ) -> None: ...
116
+ @overload
117
+ def __init__(
118
+ self,
119
+ converter: Callable[[In, AttrsInstance], Out],
120
+ *,
121
+ takes_self: Literal[True],
122
+ ) -> None: ...
123
+
124
+ class Attribute(Generic[_T]):
125
+ name: str
126
+ default: _T | None
127
+ validator: _ValidatorType[_T] | None
128
+ repr: _ReprArgType
129
+ cmp: _EqOrderType
130
+ eq: _EqOrderType
131
+ order: _EqOrderType
132
+ hash: bool | None
133
+ init: bool
134
+ converter: Converter | None
135
+ metadata: dict[Any, Any]
136
+ type: type[_T] | None
137
+ kw_only: bool
138
+ on_setattr: _OnSetAttrType
139
+ alias: str | None
140
+
141
+ def evolve(self, **changes: Any) -> "Attribute[Any]": ...
142
+
143
+ # NOTE: We had several choices for the annotation to use for type arg:
144
+ # 1) Type[_T]
145
+ # - Pros: Handles simple cases correctly
146
+ # - Cons: Might produce less informative errors in the case of conflicting
147
+ # TypeVars e.g. `attr.ib(default='bad', type=int)`
148
+ # 2) Callable[..., _T]
149
+ # - Pros: Better error messages than #1 for conflicting TypeVars
150
+ # - Cons: Terrible error messages for validator checks.
151
+ # e.g. attr.ib(type=int, validator=validate_str)
152
+ # -> error: Cannot infer function type argument
153
+ # 3) type (and do all of the work in the mypy plugin)
154
+ # - Pros: Simple here, and we could customize the plugin with our own errors.
155
+ # - Cons: Would need to write mypy plugin code to handle all the cases.
156
+ # We chose option #1.
157
+
158
+ # `attr` lies about its return type to make the following possible:
159
+ # attr() -> Any
160
+ # attr(8) -> int
161
+ # attr(validator=<some callable>) -> Whatever the callable expects.
162
+ # This makes this type of assignments possible:
163
+ # x: int = attr(8)
164
+ #
165
+ # This form catches explicit None or no default but with no other arguments
166
+ # returns Any.
167
+ @overload
168
+ def attrib(
169
+ default: None = ...,
170
+ validator: None = ...,
171
+ repr: _ReprArgType = ...,
172
+ cmp: _EqOrderType | None = ...,
173
+ hash: bool | None = ...,
174
+ init: bool = ...,
175
+ metadata: Mapping[Any, Any] | None = ...,
176
+ type: None = ...,
177
+ converter: None = ...,
178
+ factory: None = ...,
179
+ kw_only: bool = ...,
180
+ eq: _EqOrderType | None = ...,
181
+ order: _EqOrderType | None = ...,
182
+ on_setattr: _OnSetAttrArgType | None = ...,
183
+ alias: str | None = ...,
184
+ ) -> Any: ...
185
+
186
+ # This form catches an explicit None or no default and infers the type from the
187
+ # other arguments.
188
+ @overload
189
+ def attrib(
190
+ default: None = ...,
191
+ validator: _ValidatorArgType[_T] | None = ...,
192
+ repr: _ReprArgType = ...,
193
+ cmp: _EqOrderType | None = ...,
194
+ hash: bool | None = ...,
195
+ init: bool = ...,
196
+ metadata: Mapping[Any, Any] | None = ...,
197
+ type: type[_T] | None = ...,
198
+ converter: _ConverterType
199
+ | list[_ConverterType]
200
+ | tuple[_ConverterType]
201
+ | None = ...,
202
+ factory: Callable[[], _T] | None = ...,
203
+ kw_only: bool = ...,
204
+ eq: _EqOrderType | None = ...,
205
+ order: _EqOrderType | None = ...,
206
+ on_setattr: _OnSetAttrArgType | None = ...,
207
+ alias: str | None = ...,
208
+ ) -> _T: ...
209
+
210
+ # This form catches an explicit default argument.
211
+ @overload
212
+ def attrib(
213
+ default: _T,
214
+ validator: _ValidatorArgType[_T] | None = ...,
215
+ repr: _ReprArgType = ...,
216
+ cmp: _EqOrderType | None = ...,
217
+ hash: bool | None = ...,
218
+ init: bool = ...,
219
+ metadata: Mapping[Any, Any] | None = ...,
220
+ type: type[_T] | None = ...,
221
+ converter: _ConverterType
222
+ | list[_ConverterType]
223
+ | tuple[_ConverterType]
224
+ | None = ...,
225
+ factory: Callable[[], _T] | None = ...,
226
+ kw_only: bool = ...,
227
+ eq: _EqOrderType | None = ...,
228
+ order: _EqOrderType | None = ...,
229
+ on_setattr: _OnSetAttrArgType | None = ...,
230
+ alias: str | None = ...,
231
+ ) -> _T: ...
232
+
233
+ # This form covers type=non-Type: e.g. forward references (str), Any
234
+ @overload
235
+ def attrib(
236
+ default: _T | None = ...,
237
+ validator: _ValidatorArgType[_T] | None = ...,
238
+ repr: _ReprArgType = ...,
239
+ cmp: _EqOrderType | None = ...,
240
+ hash: bool | None = ...,
241
+ init: bool = ...,
242
+ metadata: Mapping[Any, Any] | None = ...,
243
+ type: object = ...,
244
+ converter: _ConverterType
245
+ | list[_ConverterType]
246
+ | tuple[_ConverterType]
247
+ | None = ...,
248
+ factory: Callable[[], _T] | None = ...,
249
+ kw_only: bool = ...,
250
+ eq: _EqOrderType | None = ...,
251
+ order: _EqOrderType | None = ...,
252
+ on_setattr: _OnSetAttrArgType | None = ...,
253
+ alias: str | None = ...,
254
+ ) -> Any: ...
255
+ @overload
256
+ @dataclass_transform(order_default=True, field_specifiers=(attrib, field))
257
+ def attrs(
258
+ maybe_cls: _C,
259
+ these: dict[str, Any] | None = ...,
260
+ repr_ns: str | None = ...,
261
+ repr: bool = ...,
262
+ cmp: _EqOrderType | None = ...,
263
+ hash: bool | None = ...,
264
+ init: bool = ...,
265
+ slots: bool = ...,
266
+ frozen: bool = ...,
267
+ weakref_slot: bool = ...,
268
+ str: bool = ...,
269
+ auto_attribs: bool = ...,
270
+ kw_only: bool = ...,
271
+ cache_hash: bool = ...,
272
+ auto_exc: bool = ...,
273
+ eq: _EqOrderType | None = ...,
274
+ order: _EqOrderType | None = ...,
275
+ auto_detect: bool = ...,
276
+ collect_by_mro: bool = ...,
277
+ getstate_setstate: bool | None = ...,
278
+ on_setattr: _OnSetAttrArgType | None = ...,
279
+ field_transformer: _FieldTransformer | None = ...,
280
+ match_args: bool = ...,
281
+ unsafe_hash: bool | None = ...,
282
+ ) -> _C: ...
283
+ @overload
284
+ @dataclass_transform(order_default=True, field_specifiers=(attrib, field))
285
+ def attrs(
286
+ maybe_cls: None = ...,
287
+ these: dict[str, Any] | None = ...,
288
+ repr_ns: str | None = ...,
289
+ repr: bool = ...,
290
+ cmp: _EqOrderType | None = ...,
291
+ hash: bool | None = ...,
292
+ init: bool = ...,
293
+ slots: bool = ...,
294
+ frozen: bool = ...,
295
+ weakref_slot: bool = ...,
296
+ str: bool = ...,
297
+ auto_attribs: bool = ...,
298
+ kw_only: bool = ...,
299
+ cache_hash: bool = ...,
300
+ auto_exc: bool = ...,
301
+ eq: _EqOrderType | None = ...,
302
+ order: _EqOrderType | None = ...,
303
+ auto_detect: bool = ...,
304
+ collect_by_mro: bool = ...,
305
+ getstate_setstate: bool | None = ...,
306
+ on_setattr: _OnSetAttrArgType | None = ...,
307
+ field_transformer: _FieldTransformer | None = ...,
308
+ match_args: bool = ...,
309
+ unsafe_hash: bool | None = ...,
310
+ ) -> Callable[[_C], _C]: ...
311
+ def fields(cls: type[AttrsInstance]) -> Any: ...
312
+ def fields_dict(cls: type[AttrsInstance]) -> dict[str, Attribute[Any]]: ...
313
+ def validate(inst: AttrsInstance) -> None: ...
314
+ def resolve_types(
315
+ cls: _A,
316
+ globalns: dict[str, Any] | None = ...,
317
+ localns: dict[str, Any] | None = ...,
318
+ attribs: list[Attribute[Any]] | None = ...,
319
+ include_extras: bool = ...,
320
+ ) -> _A: ...
321
+
322
+ # TODO: add support for returning a proper attrs class from the mypy plugin
323
+ # we use Any instead of _CountingAttr so that e.g. `make_class('Foo',
324
+ # [attr.ib()])` is valid
325
+ def make_class(
326
+ name: str,
327
+ attrs: list[str] | tuple[str, ...] | dict[str, Any],
328
+ bases: tuple[type, ...] = ...,
329
+ class_body: dict[str, Any] | None = ...,
330
+ repr_ns: str | None = ...,
331
+ repr: bool = ...,
332
+ cmp: _EqOrderType | None = ...,
333
+ hash: bool | None = ...,
334
+ init: bool = ...,
335
+ slots: bool = ...,
336
+ frozen: bool = ...,
337
+ weakref_slot: bool = ...,
338
+ str: bool = ...,
339
+ auto_attribs: bool = ...,
340
+ kw_only: bool = ...,
341
+ cache_hash: bool = ...,
342
+ auto_exc: bool = ...,
343
+ eq: _EqOrderType | None = ...,
344
+ order: _EqOrderType | None = ...,
345
+ collect_by_mro: bool = ...,
346
+ on_setattr: _OnSetAttrArgType | None = ...,
347
+ field_transformer: _FieldTransformer | None = ...,
348
+ ) -> type: ...
349
+
350
+ # _funcs --
351
+
352
+ # TODO: add support for returning TypedDict from the mypy plugin
353
+ # FIXME: asdict/astuple do not honor their factory args. Waiting on one of
354
+ # these:
355
+ # https://github.com/python/mypy/issues/4236
356
+ # https://github.com/python/typing/issues/253
357
+ # XXX: remember to fix attrs.asdict/astuple too!
358
+ def asdict(
359
+ inst: AttrsInstance,
360
+ recurse: bool = ...,
361
+ filter: _FilterType[Any] | None = ...,
362
+ dict_factory: type[Mapping[Any, Any]] = ...,
363
+ retain_collection_types: bool = ...,
364
+ value_serializer: Callable[[type, Attribute[Any], Any], Any] | None = ...,
365
+ tuple_keys: bool | None = ...,
366
+ ) -> dict[str, Any]: ...
367
+
368
+ # TODO: add support for returning NamedTuple from the mypy plugin
369
+ def astuple(
370
+ inst: AttrsInstance,
371
+ recurse: bool = ...,
372
+ filter: _FilterType[Any] | None = ...,
373
+ tuple_factory: type[Sequence[Any]] = ...,
374
+ retain_collection_types: bool = ...,
375
+ ) -> tuple[Any, ...]: ...
376
+ def has(cls: type) -> TypeGuard[type[AttrsInstance]]: ...
377
+ def assoc(inst: _T, **changes: Any) -> _T: ...
378
+ def evolve(inst: _T, **changes: Any) -> _T: ...
379
+
380
+ # _config --
381
+
382
+ def set_run_validators(run: bool) -> None: ...
383
+ def get_run_validators() -> bool: ...
384
+
385
+ # aliases --
386
+
387
+ s = attributes = attrs
388
+ ib = attr = attrib
389
+ dataclass = attrs # Technically, partial(attrs, auto_attribs=True) ;)
vllm/lib/python3.10/site-packages/attr/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.23 kB). View file
 
vllm/lib/python3.10/site-packages/attr/__pycache__/_cmp.cpython-310.pyc ADDED
Binary file (4.01 kB). View file
 
vllm/lib/python3.10/site-packages/attr/__pycache__/_compat.cpython-310.pyc ADDED
Binary file (2.41 kB). View file
 
vllm/lib/python3.10/site-packages/attr/__pycache__/_config.cpython-310.pyc ADDED
Binary file (985 Bytes). View file
 
vllm/lib/python3.10/site-packages/attr/__pycache__/_funcs.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
vllm/lib/python3.10/site-packages/attr/__pycache__/_make.cpython-310.pyc ADDED
Binary file (66.7 kB). View file
 
vllm/lib/python3.10/site-packages/attr/__pycache__/_next_gen.cpython-310.pyc ADDED
Binary file (23.6 kB). View file
 
vllm/lib/python3.10/site-packages/attr/__pycache__/_version_info.cpython-310.pyc ADDED
Binary file (2.3 kB). View file
 
vllm/lib/python3.10/site-packages/attr/__pycache__/converters.cpython-310.pyc ADDED
Binary file (3.72 kB). View file
 
vllm/lib/python3.10/site-packages/attr/__pycache__/exceptions.cpython-310.pyc ADDED
Binary file (3.14 kB). View file
 
vllm/lib/python3.10/site-packages/attr/__pycache__/filters.cpython-310.pyc ADDED
Binary file (2.23 kB). View file
 
vllm/lib/python3.10/site-packages/attr/__pycache__/setters.cpython-310.pyc ADDED
Binary file (1.58 kB). View file
 
vllm/lib/python3.10/site-packages/attr/__pycache__/validators.cpython-310.pyc ADDED
Binary file (20.3 kB). View file
 
vllm/lib/python3.10/site-packages/attr/_cmp.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+
4
+ import functools
5
+ import types
6
+
7
+ from ._make import _make_ne
8
+
9
+
10
+ _operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="}
11
+
12
+
13
+ def cmp_using(
14
+ eq=None,
15
+ lt=None,
16
+ le=None,
17
+ gt=None,
18
+ ge=None,
19
+ require_same_type=True,
20
+ class_name="Comparable",
21
+ ):
22
+ """
23
+ Create a class that can be passed into `attrs.field`'s ``eq``, ``order``,
24
+ and ``cmp`` arguments to customize field comparison.
25
+
26
+ The resulting class will have a full set of ordering methods if at least
27
+ one of ``{lt, le, gt, ge}`` and ``eq`` are provided.
28
+
29
+ Args:
30
+ eq (typing.Callable | None):
31
+ Callable used to evaluate equality of two objects.
32
+
33
+ lt (typing.Callable | None):
34
+ Callable used to evaluate whether one object is less than another
35
+ object.
36
+
37
+ le (typing.Callable | None):
38
+ Callable used to evaluate whether one object is less than or equal
39
+ to another object.
40
+
41
+ gt (typing.Callable | None):
42
+ Callable used to evaluate whether one object is greater than
43
+ another object.
44
+
45
+ ge (typing.Callable | None):
46
+ Callable used to evaluate whether one object is greater than or
47
+ equal to another object.
48
+
49
+ require_same_type (bool):
50
+ When `True`, equality and ordering methods will return
51
+ `NotImplemented` if objects are not of the same type.
52
+
53
+ class_name (str | None): Name of class. Defaults to "Comparable".
54
+
55
+ See `comparison` for more details.
56
+
57
+ .. versionadded:: 21.1.0
58
+ """
59
+
60
+ body = {
61
+ "__slots__": ["value"],
62
+ "__init__": _make_init(),
63
+ "_requirements": [],
64
+ "_is_comparable_to": _is_comparable_to,
65
+ }
66
+
67
+ # Add operations.
68
+ num_order_functions = 0
69
+ has_eq_function = False
70
+
71
+ if eq is not None:
72
+ has_eq_function = True
73
+ body["__eq__"] = _make_operator("eq", eq)
74
+ body["__ne__"] = _make_ne()
75
+
76
+ if lt is not None:
77
+ num_order_functions += 1
78
+ body["__lt__"] = _make_operator("lt", lt)
79
+
80
+ if le is not None:
81
+ num_order_functions += 1
82
+ body["__le__"] = _make_operator("le", le)
83
+
84
+ if gt is not None:
85
+ num_order_functions += 1
86
+ body["__gt__"] = _make_operator("gt", gt)
87
+
88
+ if ge is not None:
89
+ num_order_functions += 1
90
+ body["__ge__"] = _make_operator("ge", ge)
91
+
92
+ type_ = types.new_class(
93
+ class_name, (object,), {}, lambda ns: ns.update(body)
94
+ )
95
+
96
+ # Add same type requirement.
97
+ if require_same_type:
98
+ type_._requirements.append(_check_same_type)
99
+
100
+ # Add total ordering if at least one operation was defined.
101
+ if 0 < num_order_functions < 4:
102
+ if not has_eq_function:
103
+ # functools.total_ordering requires __eq__ to be defined,
104
+ # so raise early error here to keep a nice stack.
105
+ msg = "eq must be define is order to complete ordering from lt, le, gt, ge."
106
+ raise ValueError(msg)
107
+ type_ = functools.total_ordering(type_)
108
+
109
+ return type_
110
+
111
+
112
+ def _make_init():
113
+ """
114
+ Create __init__ method.
115
+ """
116
+
117
+ def __init__(self, value):
118
+ """
119
+ Initialize object with *value*.
120
+ """
121
+ self.value = value
122
+
123
+ return __init__
124
+
125
+
126
+ def _make_operator(name, func):
127
+ """
128
+ Create operator method.
129
+ """
130
+
131
+ def method(self, other):
132
+ if not self._is_comparable_to(other):
133
+ return NotImplemented
134
+
135
+ result = func(self.value, other.value)
136
+ if result is NotImplemented:
137
+ return NotImplemented
138
+
139
+ return result
140
+
141
+ method.__name__ = f"__{name}__"
142
+ method.__doc__ = (
143
+ f"Return a {_operation_names[name]} b. Computed by attrs."
144
+ )
145
+
146
+ return method
147
+
148
+
149
+ def _is_comparable_to(self, other):
150
+ """
151
+ Check whether `other` is comparable to `self`.
152
+ """
153
+ return all(func(self, other) for func in self._requirements)
154
+
155
+
156
+ def _check_same_type(self, other):
157
+ """
158
+ Return True if *self* and *other* are of the same type, False otherwise.
159
+ """
160
+ return other.value.__class__ is self.value.__class__
vllm/lib/python3.10/site-packages/attr/_cmp.pyi ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable
2
+
3
+ _CompareWithType = Callable[[Any, Any], bool]
4
+
5
+ def cmp_using(
6
+ eq: _CompareWithType | None = ...,
7
+ lt: _CompareWithType | None = ...,
8
+ le: _CompareWithType | None = ...,
9
+ gt: _CompareWithType | None = ...,
10
+ ge: _CompareWithType | None = ...,
11
+ require_same_type: bool = ...,
12
+ class_name: str = ...,
13
+ ) -> type: ...
vllm/lib/python3.10/site-packages/attr/_compat.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ import inspect
4
+ import platform
5
+ import sys
6
+ import threading
7
+
8
+ from collections.abc import Mapping, Sequence # noqa: F401
9
+ from typing import _GenericAlias
10
+
11
+
12
+ PYPY = platform.python_implementation() == "PyPy"
13
+ PY_3_9_PLUS = sys.version_info[:2] >= (3, 9)
14
+ PY_3_10_PLUS = sys.version_info[:2] >= (3, 10)
15
+ PY_3_11_PLUS = sys.version_info[:2] >= (3, 11)
16
+ PY_3_12_PLUS = sys.version_info[:2] >= (3, 12)
17
+ PY_3_13_PLUS = sys.version_info[:2] >= (3, 13)
18
+ PY_3_14_PLUS = sys.version_info[:2] >= (3, 14)
19
+
20
+
21
+ if PY_3_14_PLUS: # pragma: no cover
22
+ import annotationlib
23
+
24
+ _get_annotations = annotationlib.get_annotations
25
+
26
+ else:
27
+
28
+ def _get_annotations(cls):
29
+ """
30
+ Get annotations for *cls*.
31
+ """
32
+ return cls.__dict__.get("__annotations__", {})
33
+
34
+
35
+ class _AnnotationExtractor:
36
+ """
37
+ Extract type annotations from a callable, returning None whenever there
38
+ is none.
39
+ """
40
+
41
+ __slots__ = ["sig"]
42
+
43
+ def __init__(self, callable):
44
+ try:
45
+ self.sig = inspect.signature(callable)
46
+ except (ValueError, TypeError): # inspect failed
47
+ self.sig = None
48
+
49
+ def get_first_param_type(self):
50
+ """
51
+ Return the type annotation of the first argument if it's not empty.
52
+ """
53
+ if not self.sig:
54
+ return None
55
+
56
+ params = list(self.sig.parameters.values())
57
+ if params and params[0].annotation is not inspect.Parameter.empty:
58
+ return params[0].annotation
59
+
60
+ return None
61
+
62
+ def get_return_type(self):
63
+ """
64
+ Return the return type if it's not empty.
65
+ """
66
+ if (
67
+ self.sig
68
+ and self.sig.return_annotation is not inspect.Signature.empty
69
+ ):
70
+ return self.sig.return_annotation
71
+
72
+ return None
73
+
74
+
75
+ # Thread-local global to track attrs instances which are already being repr'd.
76
+ # This is needed because there is no other (thread-safe) way to pass info
77
+ # about the instances that are already being repr'd through the call stack
78
+ # in order to ensure we don't perform infinite recursion.
79
+ #
80
+ # For instance, if an instance contains a dict which contains that instance,
81
+ # we need to know that we're already repr'ing the outside instance from within
82
+ # the dict's repr() call.
83
+ #
84
+ # This lives here rather than in _make.py so that the functions in _make.py
85
+ # don't have a direct reference to the thread-local in their globals dict.
86
+ # If they have such a reference, it breaks cloudpickle.
87
+ repr_context = threading.local()
88
+
89
+
90
+ def get_generic_base(cl):
91
+ """If this is a generic class (A[str]), return the generic base for it."""
92
+ if cl.__class__ is _GenericAlias:
93
+ return cl.__origin__
94
+ return None
vllm/lib/python3.10/site-packages/attr/_config.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ __all__ = ["get_run_validators", "set_run_validators"]
4
+
5
+ _run_validators = True
6
+
7
+
8
+ def set_run_validators(run):
9
+ """
10
+ Set whether or not validators are run. By default, they are run.
11
+
12
+ .. deprecated:: 21.3.0 It will not be removed, but it also will not be
13
+ moved to new ``attrs`` namespace. Use `attrs.validators.set_disabled()`
14
+ instead.
15
+ """
16
+ if not isinstance(run, bool):
17
+ msg = "'run' must be bool."
18
+ raise TypeError(msg)
19
+ global _run_validators
20
+ _run_validators = run
21
+
22
+
23
+ def get_run_validators():
24
+ """
25
+ Return whether or not validators are run.
26
+
27
+ .. deprecated:: 21.3.0 It will not be removed, but it also will not be
28
+ moved to new ``attrs`` namespace. Use `attrs.validators.get_disabled()`
29
+ instead.
30
+ """
31
+ return _run_validators
vllm/lib/python3.10/site-packages/attr/_funcs.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+
4
+ import copy
5
+
6
+ from ._compat import PY_3_9_PLUS, get_generic_base
7
+ from ._make import _OBJ_SETATTR, NOTHING, fields
8
+ from .exceptions import AttrsAttributeNotFoundError
9
+
10
+
11
+ def asdict(
12
+ inst,
13
+ recurse=True,
14
+ filter=None,
15
+ dict_factory=dict,
16
+ retain_collection_types=False,
17
+ value_serializer=None,
18
+ ):
19
+ """
20
+ Return the *attrs* attribute values of *inst* as a dict.
21
+
22
+ Optionally recurse into other *attrs*-decorated classes.
23
+
24
+ Args:
25
+ inst: Instance of an *attrs*-decorated class.
26
+
27
+ recurse (bool): Recurse into classes that are also *attrs*-decorated.
28
+
29
+ filter (~typing.Callable):
30
+ A callable whose return code determines whether an attribute or
31
+ element is included (`True`) or dropped (`False`). Is called with
32
+ the `attrs.Attribute` as the first argument and the value as the
33
+ second argument.
34
+
35
+ dict_factory (~typing.Callable):
36
+ A callable to produce dictionaries from. For example, to produce
37
+ ordered dictionaries instead of normal Python dictionaries, pass in
38
+ ``collections.OrderedDict``.
39
+
40
+ retain_collection_types (bool):
41
+ Do not convert to `list` when encountering an attribute whose type
42
+ is `tuple` or `set`. Only meaningful if *recurse* is `True`.
43
+
44
+ value_serializer (typing.Callable | None):
45
+ A hook that is called for every attribute or dict key/value. It
46
+ receives the current instance, field and value and must return the
47
+ (updated) value. The hook is run *after* the optional *filter* has
48
+ been applied.
49
+
50
+ Returns:
51
+ Return type of *dict_factory*.
52
+
53
+ Raises:
54
+ attrs.exceptions.NotAnAttrsClassError:
55
+ If *cls* is not an *attrs* class.
56
+
57
+ .. versionadded:: 16.0.0 *dict_factory*
58
+ .. versionadded:: 16.1.0 *retain_collection_types*
59
+ .. versionadded:: 20.3.0 *value_serializer*
60
+ .. versionadded:: 21.3.0
61
+ If a dict has a collection for a key, it is serialized as a tuple.
62
+ """
63
+ attrs = fields(inst.__class__)
64
+ rv = dict_factory()
65
+ for a in attrs:
66
+ v = getattr(inst, a.name)
67
+ if filter is not None and not filter(a, v):
68
+ continue
69
+
70
+ if value_serializer is not None:
71
+ v = value_serializer(inst, a, v)
72
+
73
+ if recurse is True:
74
+ if has(v.__class__):
75
+ rv[a.name] = asdict(
76
+ v,
77
+ recurse=True,
78
+ filter=filter,
79
+ dict_factory=dict_factory,
80
+ retain_collection_types=retain_collection_types,
81
+ value_serializer=value_serializer,
82
+ )
83
+ elif isinstance(v, (tuple, list, set, frozenset)):
84
+ cf = v.__class__ if retain_collection_types is True else list
85
+ items = [
86
+ _asdict_anything(
87
+ i,
88
+ is_key=False,
89
+ filter=filter,
90
+ dict_factory=dict_factory,
91
+ retain_collection_types=retain_collection_types,
92
+ value_serializer=value_serializer,
93
+ )
94
+ for i in v
95
+ ]
96
+ try:
97
+ rv[a.name] = cf(items)
98
+ except TypeError:
99
+ if not issubclass(cf, tuple):
100
+ raise
101
+ # Workaround for TypeError: cf.__new__() missing 1 required
102
+ # positional argument (which appears, for a namedturle)
103
+ rv[a.name] = cf(*items)
104
+ elif isinstance(v, dict):
105
+ df = dict_factory
106
+ rv[a.name] = df(
107
+ (
108
+ _asdict_anything(
109
+ kk,
110
+ is_key=True,
111
+ filter=filter,
112
+ dict_factory=df,
113
+ retain_collection_types=retain_collection_types,
114
+ value_serializer=value_serializer,
115
+ ),
116
+ _asdict_anything(
117
+ vv,
118
+ is_key=False,
119
+ filter=filter,
120
+ dict_factory=df,
121
+ retain_collection_types=retain_collection_types,
122
+ value_serializer=value_serializer,
123
+ ),
124
+ )
125
+ for kk, vv in v.items()
126
+ )
127
+ else:
128
+ rv[a.name] = v
129
+ else:
130
+ rv[a.name] = v
131
+ return rv
132
+
133
+
134
+ def _asdict_anything(
135
+ val,
136
+ is_key,
137
+ filter,
138
+ dict_factory,
139
+ retain_collection_types,
140
+ value_serializer,
141
+ ):
142
+ """
143
+ ``asdict`` only works on attrs instances, this works on anything.
144
+ """
145
+ if getattr(val.__class__, "__attrs_attrs__", None) is not None:
146
+ # Attrs class.
147
+ rv = asdict(
148
+ val,
149
+ recurse=True,
150
+ filter=filter,
151
+ dict_factory=dict_factory,
152
+ retain_collection_types=retain_collection_types,
153
+ value_serializer=value_serializer,
154
+ )
155
+ elif isinstance(val, (tuple, list, set, frozenset)):
156
+ if retain_collection_types is True:
157
+ cf = val.__class__
158
+ elif is_key:
159
+ cf = tuple
160
+ else:
161
+ cf = list
162
+
163
+ rv = cf(
164
+ [
165
+ _asdict_anything(
166
+ i,
167
+ is_key=False,
168
+ filter=filter,
169
+ dict_factory=dict_factory,
170
+ retain_collection_types=retain_collection_types,
171
+ value_serializer=value_serializer,
172
+ )
173
+ for i in val
174
+ ]
175
+ )
176
+ elif isinstance(val, dict):
177
+ df = dict_factory
178
+ rv = df(
179
+ (
180
+ _asdict_anything(
181
+ kk,
182
+ is_key=True,
183
+ filter=filter,
184
+ dict_factory=df,
185
+ retain_collection_types=retain_collection_types,
186
+ value_serializer=value_serializer,
187
+ ),
188
+ _asdict_anything(
189
+ vv,
190
+ is_key=False,
191
+ filter=filter,
192
+ dict_factory=df,
193
+ retain_collection_types=retain_collection_types,
194
+ value_serializer=value_serializer,
195
+ ),
196
+ )
197
+ for kk, vv in val.items()
198
+ )
199
+ else:
200
+ rv = val
201
+ if value_serializer is not None:
202
+ rv = value_serializer(None, None, rv)
203
+
204
+ return rv
205
+
206
+
207
+ def astuple(
208
+ inst,
209
+ recurse=True,
210
+ filter=None,
211
+ tuple_factory=tuple,
212
+ retain_collection_types=False,
213
+ ):
214
+ """
215
+ Return the *attrs* attribute values of *inst* as a tuple.
216
+
217
+ Optionally recurse into other *attrs*-decorated classes.
218
+
219
+ Args:
220
+ inst: Instance of an *attrs*-decorated class.
221
+
222
+ recurse (bool):
223
+ Recurse into classes that are also *attrs*-decorated.
224
+
225
+ filter (~typing.Callable):
226
+ A callable whose return code determines whether an attribute or
227
+ element is included (`True`) or dropped (`False`). Is called with
228
+ the `attrs.Attribute` as the first argument and the value as the
229
+ second argument.
230
+
231
+ tuple_factory (~typing.Callable):
232
+ A callable to produce tuples from. For example, to produce lists
233
+ instead of tuples.
234
+
235
+ retain_collection_types (bool):
236
+ Do not convert to `list` or `dict` when encountering an attribute
237
+ which type is `tuple`, `dict` or `set`. Only meaningful if
238
+ *recurse* is `True`.
239
+
240
+ Returns:
241
+ Return type of *tuple_factory*
242
+
243
+ Raises:
244
+ attrs.exceptions.NotAnAttrsClassError:
245
+ If *cls* is not an *attrs* class.
246
+
247
+ .. versionadded:: 16.2.0
248
+ """
249
+ attrs = fields(inst.__class__)
250
+ rv = []
251
+ retain = retain_collection_types # Very long. :/
252
+ for a in attrs:
253
+ v = getattr(inst, a.name)
254
+ if filter is not None and not filter(a, v):
255
+ continue
256
+ if recurse is True:
257
+ if has(v.__class__):
258
+ rv.append(
259
+ astuple(
260
+ v,
261
+ recurse=True,
262
+ filter=filter,
263
+ tuple_factory=tuple_factory,
264
+ retain_collection_types=retain,
265
+ )
266
+ )
267
+ elif isinstance(v, (tuple, list, set, frozenset)):
268
+ cf = v.__class__ if retain is True else list
269
+ items = [
270
+ (
271
+ astuple(
272
+ j,
273
+ recurse=True,
274
+ filter=filter,
275
+ tuple_factory=tuple_factory,
276
+ retain_collection_types=retain,
277
+ )
278
+ if has(j.__class__)
279
+ else j
280
+ )
281
+ for j in v
282
+ ]
283
+ try:
284
+ rv.append(cf(items))
285
+ except TypeError:
286
+ if not issubclass(cf, tuple):
287
+ raise
288
+ # Workaround for TypeError: cf.__new__() missing 1 required
289
+ # positional argument (which appears, for a namedturle)
290
+ rv.append(cf(*items))
291
+ elif isinstance(v, dict):
292
+ df = v.__class__ if retain is True else dict
293
+ rv.append(
294
+ df(
295
+ (
296
+ (
297
+ astuple(
298
+ kk,
299
+ tuple_factory=tuple_factory,
300
+ retain_collection_types=retain,
301
+ )
302
+ if has(kk.__class__)
303
+ else kk
304
+ ),
305
+ (
306
+ astuple(
307
+ vv,
308
+ tuple_factory=tuple_factory,
309
+ retain_collection_types=retain,
310
+ )
311
+ if has(vv.__class__)
312
+ else vv
313
+ ),
314
+ )
315
+ for kk, vv in v.items()
316
+ )
317
+ )
318
+ else:
319
+ rv.append(v)
320
+ else:
321
+ rv.append(v)
322
+
323
+ return rv if tuple_factory is list else tuple_factory(rv)
324
+
325
+
326
+ def has(cls):
327
+ """
328
+ Check whether *cls* is a class with *attrs* attributes.
329
+
330
+ Args:
331
+ cls (type): Class to introspect.
332
+
333
+ Raises:
334
+ TypeError: If *cls* is not a class.
335
+
336
+ Returns:
337
+ bool:
338
+ """
339
+ attrs = getattr(cls, "__attrs_attrs__", None)
340
+ if attrs is not None:
341
+ return True
342
+
343
+ # No attrs, maybe it's a specialized generic (A[str])?
344
+ generic_base = get_generic_base(cls)
345
+ if generic_base is not None:
346
+ generic_attrs = getattr(generic_base, "__attrs_attrs__", None)
347
+ if generic_attrs is not None:
348
+ # Stick it on here for speed next time.
349
+ cls.__attrs_attrs__ = generic_attrs
350
+ return generic_attrs is not None
351
+ return False
352
+
353
+
354
+ def assoc(inst, **changes):
355
+ """
356
+ Copy *inst* and apply *changes*.
357
+
358
+ This is different from `evolve` that applies the changes to the arguments
359
+ that create the new instance.
360
+
361
+ `evolve`'s behavior is preferable, but there are `edge cases`_ where it
362
+ doesn't work. Therefore `assoc` is deprecated, but will not be removed.
363
+
364
+ .. _`edge cases`: https://github.com/python-attrs/attrs/issues/251
365
+
366
+ Args:
367
+ inst: Instance of a class with *attrs* attributes.
368
+
369
+ changes: Keyword changes in the new copy.
370
+
371
+ Returns:
372
+ A copy of inst with *changes* incorporated.
373
+
374
+ Raises:
375
+ attrs.exceptions.AttrsAttributeNotFoundError:
376
+ If *attr_name* couldn't be found on *cls*.
377
+
378
+ attrs.exceptions.NotAnAttrsClassError:
379
+ If *cls* is not an *attrs* class.
380
+
381
+ .. deprecated:: 17.1.0
382
+ Use `attrs.evolve` instead if you can. This function will not be
383
+ removed du to the slightly different approach compared to
384
+ `attrs.evolve`, though.
385
+ """
386
+ new = copy.copy(inst)
387
+ attrs = fields(inst.__class__)
388
+ for k, v in changes.items():
389
+ a = getattr(attrs, k, NOTHING)
390
+ if a is NOTHING:
391
+ msg = f"{k} is not an attrs attribute on {new.__class__}."
392
+ raise AttrsAttributeNotFoundError(msg)
393
+ _OBJ_SETATTR(new, k, v)
394
+ return new
395
+
396
+
397
+ def resolve_types(
398
+ cls, globalns=None, localns=None, attribs=None, include_extras=True
399
+ ):
400
+ """
401
+ Resolve any strings and forward annotations in type annotations.
402
+
403
+ This is only required if you need concrete types in :class:`Attribute`'s
404
+ *type* field. In other words, you don't need to resolve your types if you
405
+ only use them for static type checking.
406
+
407
+ With no arguments, names will be looked up in the module in which the class
408
+ was created. If this is not what you want, for example, if the name only
409
+ exists inside a method, you may pass *globalns* or *localns* to specify
410
+ other dictionaries in which to look up these names. See the docs of
411
+ `typing.get_type_hints` for more details.
412
+
413
+ Args:
414
+ cls (type): Class to resolve.
415
+
416
+ globalns (dict | None): Dictionary containing global variables.
417
+
418
+ localns (dict | None): Dictionary containing local variables.
419
+
420
+ attribs (list | None):
421
+ List of attribs for the given class. This is necessary when calling
422
+ from inside a ``field_transformer`` since *cls* is not an *attrs*
423
+ class yet.
424
+
425
+ include_extras (bool):
426
+ Resolve more accurately, if possible. Pass ``include_extras`` to
427
+ ``typing.get_hints``, if supported by the typing module. On
428
+ supported Python versions (3.9+), this resolves the types more
429
+ accurately.
430
+
431
+ Raises:
432
+ TypeError: If *cls* is not a class.
433
+
434
+ attrs.exceptions.NotAnAttrsClassError:
435
+ If *cls* is not an *attrs* class and you didn't pass any attribs.
436
+
437
+ NameError: If types cannot be resolved because of missing variables.
438
+
439
+ Returns:
440
+ *cls* so you can use this function also as a class decorator. Please
441
+ note that you have to apply it **after** `attrs.define`. That means the
442
+ decorator has to come in the line **before** `attrs.define`.
443
+
444
+ .. versionadded:: 20.1.0
445
+ .. versionadded:: 21.1.0 *attribs*
446
+ .. versionadded:: 23.1.0 *include_extras*
447
+ """
448
+ # Since calling get_type_hints is expensive we cache whether we've
449
+ # done it already.
450
+ if getattr(cls, "__attrs_types_resolved__", None) != cls:
451
+ import typing
452
+
453
+ kwargs = {"globalns": globalns, "localns": localns}
454
+
455
+ if PY_3_9_PLUS:
456
+ kwargs["include_extras"] = include_extras
457
+
458
+ hints = typing.get_type_hints(cls, **kwargs)
459
+ for field in fields(cls) if attribs is None else attribs:
460
+ if field.name in hints:
461
+ # Since fields have been frozen we must work around it.
462
+ _OBJ_SETATTR(field, "type", hints[field.name])
463
+ # We store the class we resolved so that subclasses know they haven't
464
+ # been resolved.
465
+ cls.__attrs_types_resolved__ = cls
466
+
467
+ # Return the class so you can use it as a decorator too.
468
+ return cls
vllm/lib/python3.10/site-packages/attr/_make.py ADDED
@@ -0,0 +1,3055 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ from __future__ import annotations
4
+
5
+ import abc
6
+ import contextlib
7
+ import copy
8
+ import enum
9
+ import functools
10
+ import inspect
11
+ import itertools
12
+ import linecache
13
+ import sys
14
+ import types
15
+ import typing
16
+
17
+ from operator import itemgetter
18
+
19
+ # We need to import _compat itself in addition to the _compat members to avoid
20
+ # having the thread-local in the globals here.
21
+ from . import _compat, _config, setters
22
+ from ._compat import (
23
+ PY_3_10_PLUS,
24
+ PY_3_11_PLUS,
25
+ PY_3_13_PLUS,
26
+ _AnnotationExtractor,
27
+ _get_annotations,
28
+ get_generic_base,
29
+ )
30
+ from .exceptions import (
31
+ DefaultAlreadySetError,
32
+ FrozenInstanceError,
33
+ NotAnAttrsClassError,
34
+ UnannotatedAttributeError,
35
+ )
36
+
37
+
38
+ # This is used at least twice, so cache it here.
39
+ _OBJ_SETATTR = object.__setattr__
40
+ _INIT_FACTORY_PAT = "__attr_factory_%s"
41
+ _CLASSVAR_PREFIXES = (
42
+ "typing.ClassVar",
43
+ "t.ClassVar",
44
+ "ClassVar",
45
+ "typing_extensions.ClassVar",
46
+ )
47
+ # we don't use a double-underscore prefix because that triggers
48
+ # name mangling when trying to create a slot for the field
49
+ # (when slots=True)
50
+ _HASH_CACHE_FIELD = "_attrs_cached_hash"
51
+
52
+ _EMPTY_METADATA_SINGLETON = types.MappingProxyType({})
53
+
54
+ # Unique object for unequivocal getattr() defaults.
55
+ _SENTINEL = object()
56
+
57
+ _DEFAULT_ON_SETATTR = setters.pipe(setters.convert, setters.validate)
58
+
59
+
60
+ class _Nothing(enum.Enum):
61
+ """
62
+ Sentinel to indicate the lack of a value when `None` is ambiguous.
63
+
64
+ If extending attrs, you can use ``typing.Literal[NOTHING]`` to show
65
+ that a value may be ``NOTHING``.
66
+
67
+ .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.
68
+ .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.
69
+ """
70
+
71
+ NOTHING = enum.auto()
72
+
73
+ def __repr__(self):
74
+ return "NOTHING"
75
+
76
+ def __bool__(self):
77
+ return False
78
+
79
+
80
+ NOTHING = _Nothing.NOTHING
81
+ """
82
+ Sentinel to indicate the lack of a value when `None` is ambiguous.
83
+
84
+ When using in 3rd party code, use `attrs.NothingType` for type annotations.
85
+ """
86
+
87
+
88
+ class _CacheHashWrapper(int):
89
+ """
90
+ An integer subclass that pickles / copies as None
91
+
92
+ This is used for non-slots classes with ``cache_hash=True``, to avoid
93
+ serializing a potentially (even likely) invalid hash value. Since `None`
94
+ is the default value for uncalculated hashes, whenever this is copied,
95
+ the copy's value for the hash should automatically reset.
96
+
97
+ See GH #613 for more details.
98
+ """
99
+
100
+ def __reduce__(self, _none_constructor=type(None), _args=()): # noqa: B008
101
+ return _none_constructor, _args
102
+
103
+
104
+ def attrib(
105
+ default=NOTHING,
106
+ validator=None,
107
+ repr=True,
108
+ cmp=None,
109
+ hash=None,
110
+ init=True,
111
+ metadata=None,
112
+ type=None,
113
+ converter=None,
114
+ factory=None,
115
+ kw_only=False,
116
+ eq=None,
117
+ order=None,
118
+ on_setattr=None,
119
+ alias=None,
120
+ ):
121
+ """
122
+ Create a new field / attribute on a class.
123
+
124
+ Identical to `attrs.field`, except it's not keyword-only.
125
+
126
+ Consider using `attrs.field` in new code (``attr.ib`` will *never* go away,
127
+ though).
128
+
129
+ .. warning::
130
+
131
+ Does **nothing** unless the class is also decorated with
132
+ `attr.s` (or similar)!
133
+
134
+
135
+ .. versionadded:: 15.2.0 *convert*
136
+ .. versionadded:: 16.3.0 *metadata*
137
+ .. versionchanged:: 17.1.0 *validator* can be a ``list`` now.
138
+ .. versionchanged:: 17.1.0
139
+ *hash* is `None` and therefore mirrors *eq* by default.
140
+ .. versionadded:: 17.3.0 *type*
141
+ .. deprecated:: 17.4.0 *convert*
142
+ .. versionadded:: 17.4.0
143
+ *converter* as a replacement for the deprecated *convert* to achieve
144
+ consistency with other noun-based arguments.
145
+ .. versionadded:: 18.1.0
146
+ ``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``.
147
+ .. versionadded:: 18.2.0 *kw_only*
148
+ .. versionchanged:: 19.2.0 *convert* keyword argument removed.
149
+ .. versionchanged:: 19.2.0 *repr* also accepts a custom callable.
150
+ .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01.
151
+ .. versionadded:: 19.2.0 *eq* and *order*
152
+ .. versionadded:: 20.1.0 *on_setattr*
153
+ .. versionchanged:: 20.3.0 *kw_only* backported to Python 2
154
+ .. versionchanged:: 21.1.0
155
+ *eq*, *order*, and *cmp* also accept a custom callable
156
+ .. versionchanged:: 21.1.0 *cmp* undeprecated
157
+ .. versionadded:: 22.2.0 *alias*
158
+ """
159
+ eq, eq_key, order, order_key = _determine_attrib_eq_order(
160
+ cmp, eq, order, True
161
+ )
162
+
163
+ if hash is not None and hash is not True and hash is not False:
164
+ msg = "Invalid value for hash. Must be True, False, or None."
165
+ raise TypeError(msg)
166
+
167
+ if factory is not None:
168
+ if default is not NOTHING:
169
+ msg = (
170
+ "The `default` and `factory` arguments are mutually exclusive."
171
+ )
172
+ raise ValueError(msg)
173
+ if not callable(factory):
174
+ msg = "The `factory` argument must be a callable."
175
+ raise ValueError(msg)
176
+ default = Factory(factory)
177
+
178
+ if metadata is None:
179
+ metadata = {}
180
+
181
+ # Apply syntactic sugar by auto-wrapping.
182
+ if isinstance(on_setattr, (list, tuple)):
183
+ on_setattr = setters.pipe(*on_setattr)
184
+
185
+ if validator and isinstance(validator, (list, tuple)):
186
+ validator = and_(*validator)
187
+
188
+ if converter and isinstance(converter, (list, tuple)):
189
+ converter = pipe(*converter)
190
+
191
+ return _CountingAttr(
192
+ default=default,
193
+ validator=validator,
194
+ repr=repr,
195
+ cmp=None,
196
+ hash=hash,
197
+ init=init,
198
+ converter=converter,
199
+ metadata=metadata,
200
+ type=type,
201
+ kw_only=kw_only,
202
+ eq=eq,
203
+ eq_key=eq_key,
204
+ order=order,
205
+ order_key=order_key,
206
+ on_setattr=on_setattr,
207
+ alias=alias,
208
+ )
209
+
210
+
211
+ def _compile_and_eval(script, globs, locs=None, filename=""):
212
+ """
213
+ Evaluate the script with the given global (globs) and local (locs)
214
+ variables.
215
+ """
216
+ bytecode = compile(script, filename, "exec")
217
+ eval(bytecode, globs, locs)
218
+
219
+
220
+ def _make_method(name, script, filename, globs, locals=None):
221
+ """
222
+ Create the method with the script given and return the method object.
223
+ """
224
+ locs = {} if locals is None else locals
225
+
226
+ # In order of debuggers like PDB being able to step through the code,
227
+ # we add a fake linecache entry.
228
+ count = 1
229
+ base_filename = filename
230
+ while True:
231
+ linecache_tuple = (
232
+ len(script),
233
+ None,
234
+ script.splitlines(True),
235
+ filename,
236
+ )
237
+ old_val = linecache.cache.setdefault(filename, linecache_tuple)
238
+ if old_val == linecache_tuple:
239
+ break
240
+
241
+ filename = f"{base_filename[:-1]}-{count}>"
242
+ count += 1
243
+
244
+ _compile_and_eval(script, globs, locs, filename)
245
+
246
+ return locs[name]
247
+
248
+
249
+ def _make_attr_tuple_class(cls_name, attr_names):
250
+ """
251
+ Create a tuple subclass to hold `Attribute`s for an `attrs` class.
252
+
253
+ The subclass is a bare tuple with properties for names.
254
+
255
+ class MyClassAttributes(tuple):
256
+ __slots__ = ()
257
+ x = property(itemgetter(0))
258
+ """
259
+ attr_class_name = f"{cls_name}Attributes"
260
+ attr_class_template = [
261
+ f"class {attr_class_name}(tuple):",
262
+ " __slots__ = ()",
263
+ ]
264
+ if attr_names:
265
+ for i, attr_name in enumerate(attr_names):
266
+ attr_class_template.append(
267
+ f" {attr_name} = _attrs_property(_attrs_itemgetter({i}))"
268
+ )
269
+ else:
270
+ attr_class_template.append(" pass")
271
+ globs = {"_attrs_itemgetter": itemgetter, "_attrs_property": property}
272
+ _compile_and_eval("\n".join(attr_class_template), globs)
273
+ return globs[attr_class_name]
274
+
275
+
276
+ # Tuple class for extracted attributes from a class definition.
277
+ # `base_attrs` is a subset of `attrs`.
278
+ _Attributes = _make_attr_tuple_class(
279
+ "_Attributes",
280
+ [
281
+ # all attributes to build dunder methods for
282
+ "attrs",
283
+ # attributes that have been inherited
284
+ "base_attrs",
285
+ # map inherited attributes to their originating classes
286
+ "base_attrs_map",
287
+ ],
288
+ )
289
+
290
+
291
+ def _is_class_var(annot):
292
+ """
293
+ Check whether *annot* is a typing.ClassVar.
294
+
295
+ The string comparison hack is used to avoid evaluating all string
296
+ annotations which would put attrs-based classes at a performance
297
+ disadvantage compared to plain old classes.
298
+ """
299
+ annot = str(annot)
300
+
301
+ # Annotation can be quoted.
302
+ if annot.startswith(("'", '"')) and annot.endswith(("'", '"')):
303
+ annot = annot[1:-1]
304
+
305
+ return annot.startswith(_CLASSVAR_PREFIXES)
306
+
307
+
308
+ def _has_own_attribute(cls, attrib_name):
309
+ """
310
+ Check whether *cls* defines *attrib_name* (and doesn't just inherit it).
311
+ """
312
+ return attrib_name in cls.__dict__
313
+
314
+
315
+ def _collect_base_attrs(cls, taken_attr_names):
316
+ """
317
+ Collect attr.ibs from base classes of *cls*, except *taken_attr_names*.
318
+ """
319
+ base_attrs = []
320
+ base_attr_map = {} # A dictionary of base attrs to their classes.
321
+
322
+ # Traverse the MRO and collect attributes.
323
+ for base_cls in reversed(cls.__mro__[1:-1]):
324
+ for a in getattr(base_cls, "__attrs_attrs__", []):
325
+ if a.inherited or a.name in taken_attr_names:
326
+ continue
327
+
328
+ a = a.evolve(inherited=True) # noqa: PLW2901
329
+ base_attrs.append(a)
330
+ base_attr_map[a.name] = base_cls
331
+
332
+ # For each name, only keep the freshest definition i.e. the furthest at the
333
+ # back. base_attr_map is fine because it gets overwritten with every new
334
+ # instance.
335
+ filtered = []
336
+ seen = set()
337
+ for a in reversed(base_attrs):
338
+ if a.name in seen:
339
+ continue
340
+ filtered.insert(0, a)
341
+ seen.add(a.name)
342
+
343
+ return filtered, base_attr_map
344
+
345
+
346
+ def _collect_base_attrs_broken(cls, taken_attr_names):
347
+ """
348
+ Collect attr.ibs from base classes of *cls*, except *taken_attr_names*.
349
+
350
+ N.B. *taken_attr_names* will be mutated.
351
+
352
+ Adhere to the old incorrect behavior.
353
+
354
+ Notably it collects from the front and considers inherited attributes which
355
+ leads to the buggy behavior reported in #428.
356
+ """
357
+ base_attrs = []
358
+ base_attr_map = {} # A dictionary of base attrs to their classes.
359
+
360
+ # Traverse the MRO and collect attributes.
361
+ for base_cls in cls.__mro__[1:-1]:
362
+ for a in getattr(base_cls, "__attrs_attrs__", []):
363
+ if a.name in taken_attr_names:
364
+ continue
365
+
366
+ a = a.evolve(inherited=True) # noqa: PLW2901
367
+ taken_attr_names.add(a.name)
368
+ base_attrs.append(a)
369
+ base_attr_map[a.name] = base_cls
370
+
371
+ return base_attrs, base_attr_map
372
+
373
+
374
+ def _transform_attrs(
375
+ cls, these, auto_attribs, kw_only, collect_by_mro, field_transformer
376
+ ):
377
+ """
378
+ Transform all `_CountingAttr`s on a class into `Attribute`s.
379
+
380
+ If *these* is passed, use that and don't look for them on the class.
381
+
382
+ If *collect_by_mro* is True, collect them in the correct MRO order,
383
+ otherwise use the old -- incorrect -- order. See #428.
384
+
385
+ Return an `_Attributes`.
386
+ """
387
+ cd = cls.__dict__
388
+ anns = _get_annotations(cls)
389
+
390
+ if these is not None:
391
+ ca_list = list(these.items())
392
+ elif auto_attribs is True:
393
+ ca_names = {
394
+ name
395
+ for name, attr in cd.items()
396
+ if isinstance(attr, _CountingAttr)
397
+ }
398
+ ca_list = []
399
+ annot_names = set()
400
+ for attr_name, type in anns.items():
401
+ if _is_class_var(type):
402
+ continue
403
+ annot_names.add(attr_name)
404
+ a = cd.get(attr_name, NOTHING)
405
+
406
+ if not isinstance(a, _CountingAttr):
407
+ a = attrib() if a is NOTHING else attrib(default=a)
408
+ ca_list.append((attr_name, a))
409
+
410
+ unannotated = ca_names - annot_names
411
+ if len(unannotated) > 0:
412
+ raise UnannotatedAttributeError(
413
+ "The following `attr.ib`s lack a type annotation: "
414
+ + ", ".join(
415
+ sorted(unannotated, key=lambda n: cd.get(n).counter)
416
+ )
417
+ + "."
418
+ )
419
+ else:
420
+ ca_list = sorted(
421
+ (
422
+ (name, attr)
423
+ for name, attr in cd.items()
424
+ if isinstance(attr, _CountingAttr)
425
+ ),
426
+ key=lambda e: e[1].counter,
427
+ )
428
+
429
+ own_attrs = [
430
+ Attribute.from_counting_attr(
431
+ name=attr_name, ca=ca, type=anns.get(attr_name)
432
+ )
433
+ for attr_name, ca in ca_list
434
+ ]
435
+
436
+ if collect_by_mro:
437
+ base_attrs, base_attr_map = _collect_base_attrs(
438
+ cls, {a.name for a in own_attrs}
439
+ )
440
+ else:
441
+ base_attrs, base_attr_map = _collect_base_attrs_broken(
442
+ cls, {a.name for a in own_attrs}
443
+ )
444
+
445
+ if kw_only:
446
+ own_attrs = [a.evolve(kw_only=True) for a in own_attrs]
447
+ base_attrs = [a.evolve(kw_only=True) for a in base_attrs]
448
+
449
+ attrs = base_attrs + own_attrs
450
+
451
+ # Mandatory vs non-mandatory attr order only matters when they are part of
452
+ # the __init__ signature and when they aren't kw_only (which are moved to
453
+ # the end and can be mandatory or non-mandatory in any order, as they will
454
+ # be specified as keyword args anyway). Check the order of those attrs:
455
+ had_default = False
456
+ for a in (a for a in attrs if a.init is not False and a.kw_only is False):
457
+ if had_default is True and a.default is NOTHING:
458
+ msg = f"No mandatory attributes allowed after an attribute with a default value or factory. Attribute in question: {a!r}"
459
+ raise ValueError(msg)
460
+
461
+ if had_default is False and a.default is not NOTHING:
462
+ had_default = True
463
+
464
+ if field_transformer is not None:
465
+ attrs = field_transformer(cls, attrs)
466
+
467
+ # Resolve default field alias after executing field_transformer.
468
+ # This allows field_transformer to differentiate between explicit vs
469
+ # default aliases and supply their own defaults.
470
+ attrs = [
471
+ a.evolve(alias=_default_init_alias_for(a.name)) if not a.alias else a
472
+ for a in attrs
473
+ ]
474
+
475
+ # Create AttrsClass *after* applying the field_transformer since it may
476
+ # add or remove attributes!
477
+ attr_names = [a.name for a in attrs]
478
+ AttrsClass = _make_attr_tuple_class(cls.__name__, attr_names)
479
+
480
+ return _Attributes((AttrsClass(attrs), base_attrs, base_attr_map))
481
+
482
+
483
+ def _make_cached_property_getattr(cached_properties, original_getattr, cls):
484
+ lines = [
485
+ # Wrapped to get `__class__` into closure cell for super()
486
+ # (It will be replaced with the newly constructed class after construction).
487
+ "def wrapper(_cls):",
488
+ " __class__ = _cls",
489
+ " def __getattr__(self, item, cached_properties=cached_properties, original_getattr=original_getattr, _cached_setattr_get=_cached_setattr_get):",
490
+ " func = cached_properties.get(item)",
491
+ " if func is not None:",
492
+ " result = func(self)",
493
+ " _setter = _cached_setattr_get(self)",
494
+ " _setter(item, result)",
495
+ " return result",
496
+ ]
497
+ if original_getattr is not None:
498
+ lines.append(
499
+ " return original_getattr(self, item)",
500
+ )
501
+ else:
502
+ lines.extend(
503
+ [
504
+ " try:",
505
+ " return super().__getattribute__(item)",
506
+ " except AttributeError:",
507
+ " if not hasattr(super(), '__getattr__'):",
508
+ " raise",
509
+ " return super().__getattr__(item)",
510
+ " original_error = f\"'{self.__class__.__name__}' object has no attribute '{item}'\"",
511
+ " raise AttributeError(original_error)",
512
+ ]
513
+ )
514
+
515
+ lines.extend(
516
+ [
517
+ " return __getattr__",
518
+ "__getattr__ = wrapper(_cls)",
519
+ ]
520
+ )
521
+
522
+ unique_filename = _generate_unique_filename(cls, "getattr")
523
+
524
+ glob = {
525
+ "cached_properties": cached_properties,
526
+ "_cached_setattr_get": _OBJ_SETATTR.__get__,
527
+ "original_getattr": original_getattr,
528
+ }
529
+
530
+ return _make_method(
531
+ "__getattr__",
532
+ "\n".join(lines),
533
+ unique_filename,
534
+ glob,
535
+ locals={
536
+ "_cls": cls,
537
+ },
538
+ )
539
+
540
+
541
+ def _frozen_setattrs(self, name, value):
542
+ """
543
+ Attached to frozen classes as __setattr__.
544
+ """
545
+ if isinstance(self, BaseException) and name in (
546
+ "__cause__",
547
+ "__context__",
548
+ "__traceback__",
549
+ "__suppress_context__",
550
+ "__notes__",
551
+ ):
552
+ BaseException.__setattr__(self, name, value)
553
+ return
554
+
555
+ raise FrozenInstanceError
556
+
557
+
558
+ def _frozen_delattrs(self, name):
559
+ """
560
+ Attached to frozen classes as __delattr__.
561
+ """
562
+ if isinstance(self, BaseException) and name in ("__notes__",):
563
+ BaseException.__delattr__(self, name)
564
+ return
565
+
566
+ raise FrozenInstanceError
567
+
568
+
569
+ def evolve(*args, **changes):
570
+ """
571
+ Create a new instance, based on the first positional argument with
572
+ *changes* applied.
573
+
574
+ .. tip::
575
+
576
+ On Python 3.13 and later, you can also use `copy.replace` instead.
577
+
578
+ Args:
579
+
580
+ inst:
581
+ Instance of a class with *attrs* attributes. *inst* must be passed
582
+ as a positional argument.
583
+
584
+ changes:
585
+ Keyword changes in the new copy.
586
+
587
+ Returns:
588
+ A copy of inst with *changes* incorporated.
589
+
590
+ Raises:
591
+ TypeError:
592
+ If *attr_name* couldn't be found in the class ``__init__``.
593
+
594
+ attrs.exceptions.NotAnAttrsClassError:
595
+ If *cls* is not an *attrs* class.
596
+
597
+ .. versionadded:: 17.1.0
598
+ .. deprecated:: 23.1.0
599
+ It is now deprecated to pass the instance using the keyword argument
600
+ *inst*. It will raise a warning until at least April 2024, after which
601
+ it will become an error. Always pass the instance as a positional
602
+ argument.
603
+ .. versionchanged:: 24.1.0
604
+ *inst* can't be passed as a keyword argument anymore.
605
+ """
606
+ try:
607
+ (inst,) = args
608
+ except ValueError:
609
+ msg = (
610
+ f"evolve() takes 1 positional argument, but {len(args)} were given"
611
+ )
612
+ raise TypeError(msg) from None
613
+
614
+ cls = inst.__class__
615
+ attrs = fields(cls)
616
+ for a in attrs:
617
+ if not a.init:
618
+ continue
619
+ attr_name = a.name # To deal with private attributes.
620
+ init_name = a.alias
621
+ if init_name not in changes:
622
+ changes[init_name] = getattr(inst, attr_name)
623
+
624
+ return cls(**changes)
625
+
626
+
627
+ class _ClassBuilder:
628
+ """
629
+ Iteratively build *one* class.
630
+ """
631
+
632
+ __slots__ = (
633
+ "_attr_names",
634
+ "_attrs",
635
+ "_base_attr_map",
636
+ "_base_names",
637
+ "_cache_hash",
638
+ "_cls",
639
+ "_cls_dict",
640
+ "_delete_attribs",
641
+ "_frozen",
642
+ "_has_custom_setattr",
643
+ "_has_post_init",
644
+ "_has_pre_init",
645
+ "_is_exc",
646
+ "_on_setattr",
647
+ "_pre_init_has_args",
648
+ "_slots",
649
+ "_weakref_slot",
650
+ "_wrote_own_setattr",
651
+ )
652
+
653
+ def __init__(
654
+ self,
655
+ cls,
656
+ these,
657
+ slots,
658
+ frozen,
659
+ weakref_slot,
660
+ getstate_setstate,
661
+ auto_attribs,
662
+ kw_only,
663
+ cache_hash,
664
+ is_exc,
665
+ collect_by_mro,
666
+ on_setattr,
667
+ has_custom_setattr,
668
+ field_transformer,
669
+ ):
670
+ attrs, base_attrs, base_map = _transform_attrs(
671
+ cls,
672
+ these,
673
+ auto_attribs,
674
+ kw_only,
675
+ collect_by_mro,
676
+ field_transformer,
677
+ )
678
+
679
+ self._cls = cls
680
+ self._cls_dict = dict(cls.__dict__) if slots else {}
681
+ self._attrs = attrs
682
+ self._base_names = {a.name for a in base_attrs}
683
+ self._base_attr_map = base_map
684
+ self._attr_names = tuple(a.name for a in attrs)
685
+ self._slots = slots
686
+ self._frozen = frozen
687
+ self._weakref_slot = weakref_slot
688
+ self._cache_hash = cache_hash
689
+ self._has_pre_init = bool(getattr(cls, "__attrs_pre_init__", False))
690
+ self._pre_init_has_args = False
691
+ if self._has_pre_init:
692
+ # Check if the pre init method has more arguments than just `self`
693
+ # We want to pass arguments if pre init expects arguments
694
+ pre_init_func = cls.__attrs_pre_init__
695
+ pre_init_signature = inspect.signature(pre_init_func)
696
+ self._pre_init_has_args = len(pre_init_signature.parameters) > 1
697
+ self._has_post_init = bool(getattr(cls, "__attrs_post_init__", False))
698
+ self._delete_attribs = not bool(these)
699
+ self._is_exc = is_exc
700
+ self._on_setattr = on_setattr
701
+
702
+ self._has_custom_setattr = has_custom_setattr
703
+ self._wrote_own_setattr = False
704
+
705
+ self._cls_dict["__attrs_attrs__"] = self._attrs
706
+
707
+ if frozen:
708
+ self._cls_dict["__setattr__"] = _frozen_setattrs
709
+ self._cls_dict["__delattr__"] = _frozen_delattrs
710
+
711
+ self._wrote_own_setattr = True
712
+ elif on_setattr in (
713
+ _DEFAULT_ON_SETATTR,
714
+ setters.validate,
715
+ setters.convert,
716
+ ):
717
+ has_validator = has_converter = False
718
+ for a in attrs:
719
+ if a.validator is not None:
720
+ has_validator = True
721
+ if a.converter is not None:
722
+ has_converter = True
723
+
724
+ if has_validator and has_converter:
725
+ break
726
+ if (
727
+ (
728
+ on_setattr == _DEFAULT_ON_SETATTR
729
+ and not (has_validator or has_converter)
730
+ )
731
+ or (on_setattr == setters.validate and not has_validator)
732
+ or (on_setattr == setters.convert and not has_converter)
733
+ ):
734
+ # If class-level on_setattr is set to convert + validate, but
735
+ # there's no field to convert or validate, pretend like there's
736
+ # no on_setattr.
737
+ self._on_setattr = None
738
+
739
+ if getstate_setstate:
740
+ (
741
+ self._cls_dict["__getstate__"],
742
+ self._cls_dict["__setstate__"],
743
+ ) = self._make_getstate_setstate()
744
+
745
+ def __repr__(self):
746
+ return f"<_ClassBuilder(cls={self._cls.__name__})>"
747
+
748
+ def build_class(self):
749
+ """
750
+ Finalize class based on the accumulated configuration.
751
+
752
+ Builder cannot be used after calling this method.
753
+ """
754
+ if self._slots is True:
755
+ cls = self._create_slots_class()
756
+ else:
757
+ cls = self._patch_original_class()
758
+ if PY_3_10_PLUS:
759
+ cls = abc.update_abstractmethods(cls)
760
+
761
+ # The method gets only called if it's not inherited from a base class.
762
+ # _has_own_attribute does NOT work properly for classmethods.
763
+ if (
764
+ getattr(cls, "__attrs_init_subclass__", None)
765
+ and "__attrs_init_subclass__" not in cls.__dict__
766
+ ):
767
+ cls.__attrs_init_subclass__()
768
+
769
+ return cls
770
+
771
+ def _patch_original_class(self):
772
+ """
773
+ Apply accumulated methods and return the class.
774
+ """
775
+ cls = self._cls
776
+ base_names = self._base_names
777
+
778
+ # Clean class of attribute definitions (`attr.ib()`s).
779
+ if self._delete_attribs:
780
+ for name in self._attr_names:
781
+ if (
782
+ name not in base_names
783
+ and getattr(cls, name, _SENTINEL) is not _SENTINEL
784
+ ):
785
+ # An AttributeError can happen if a base class defines a
786
+ # class variable and we want to set an attribute with the
787
+ # same name by using only a type annotation.
788
+ with contextlib.suppress(AttributeError):
789
+ delattr(cls, name)
790
+
791
+ # Attach our dunder methods.
792
+ for name, value in self._cls_dict.items():
793
+ setattr(cls, name, value)
794
+
795
+ # If we've inherited an attrs __setattr__ and don't write our own,
796
+ # reset it to object's.
797
+ if not self._wrote_own_setattr and getattr(
798
+ cls, "__attrs_own_setattr__", False
799
+ ):
800
+ cls.__attrs_own_setattr__ = False
801
+
802
+ if not self._has_custom_setattr:
803
+ cls.__setattr__ = _OBJ_SETATTR
804
+
805
+ return cls
806
+
807
+ def _create_slots_class(self):
808
+ """
809
+ Build and return a new class with a `__slots__` attribute.
810
+ """
811
+ cd = {
812
+ k: v
813
+ for k, v in self._cls_dict.items()
814
+ if k not in (*tuple(self._attr_names), "__dict__", "__weakref__")
815
+ }
816
+
817
+ # If our class doesn't have its own implementation of __setattr__
818
+ # (either from the user or by us), check the bases, if one of them has
819
+ # an attrs-made __setattr__, that needs to be reset. We don't walk the
820
+ # MRO because we only care about our immediate base classes.
821
+ # XXX: This can be confused by subclassing a slotted attrs class with
822
+ # XXX: a non-attrs class and subclass the resulting class with an attrs
823
+ # XXX: class. See `test_slotted_confused` for details. For now that's
824
+ # XXX: OK with us.
825
+ if not self._wrote_own_setattr:
826
+ cd["__attrs_own_setattr__"] = False
827
+
828
+ if not self._has_custom_setattr:
829
+ for base_cls in self._cls.__bases__:
830
+ if base_cls.__dict__.get("__attrs_own_setattr__", False):
831
+ cd["__setattr__"] = _OBJ_SETATTR
832
+ break
833
+
834
+ # Traverse the MRO to collect existing slots
835
+ # and check for an existing __weakref__.
836
+ existing_slots = {}
837
+ weakref_inherited = False
838
+ for base_cls in self._cls.__mro__[1:-1]:
839
+ if base_cls.__dict__.get("__weakref__", None) is not None:
840
+ weakref_inherited = True
841
+ existing_slots.update(
842
+ {
843
+ name: getattr(base_cls, name)
844
+ for name in getattr(base_cls, "__slots__", [])
845
+ }
846
+ )
847
+
848
+ base_names = set(self._base_names)
849
+
850
+ names = self._attr_names
851
+ if (
852
+ self._weakref_slot
853
+ and "__weakref__" not in getattr(self._cls, "__slots__", ())
854
+ and "__weakref__" not in names
855
+ and not weakref_inherited
856
+ ):
857
+ names += ("__weakref__",)
858
+
859
+ cached_properties = {
860
+ name: cached_property.func
861
+ for name, cached_property in cd.items()
862
+ if isinstance(cached_property, functools.cached_property)
863
+ }
864
+
865
+ # Collect methods with a `__class__` reference that are shadowed in the new class.
866
+ # To know to update them.
867
+ additional_closure_functions_to_update = []
868
+ if cached_properties:
869
+ class_annotations = _get_annotations(self._cls)
870
+ for name, func in cached_properties.items():
871
+ # Add cached properties to names for slotting.
872
+ names += (name,)
873
+ # Clear out function from class to avoid clashing.
874
+ del cd[name]
875
+ additional_closure_functions_to_update.append(func)
876
+ annotation = inspect.signature(func).return_annotation
877
+ if annotation is not inspect.Parameter.empty:
878
+ class_annotations[name] = annotation
879
+
880
+ original_getattr = cd.get("__getattr__")
881
+ if original_getattr is not None:
882
+ additional_closure_functions_to_update.append(original_getattr)
883
+
884
+ cd["__getattr__"] = _make_cached_property_getattr(
885
+ cached_properties, original_getattr, self._cls
886
+ )
887
+
888
+ # We only add the names of attributes that aren't inherited.
889
+ # Setting __slots__ to inherited attributes wastes memory.
890
+ slot_names = [name for name in names if name not in base_names]
891
+
892
+ # There are slots for attributes from current class
893
+ # that are defined in parent classes.
894
+ # As their descriptors may be overridden by a child class,
895
+ # we collect them here and update the class dict
896
+ reused_slots = {
897
+ slot: slot_descriptor
898
+ for slot, slot_descriptor in existing_slots.items()
899
+ if slot in slot_names
900
+ }
901
+ slot_names = [name for name in slot_names if name not in reused_slots]
902
+ cd.update(reused_slots)
903
+ if self._cache_hash:
904
+ slot_names.append(_HASH_CACHE_FIELD)
905
+
906
+ cd["__slots__"] = tuple(slot_names)
907
+
908
+ cd["__qualname__"] = self._cls.__qualname__
909
+
910
+ # Create new class based on old class and our methods.
911
+ cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)
912
+
913
+ # The following is a fix for
914
+ # <https://github.com/python-attrs/attrs/issues/102>.
915
+ # If a method mentions `__class__` or uses the no-arg super(), the
916
+ # compiler will bake a reference to the class in the method itself
917
+ # as `method.__closure__`. Since we replace the class with a
918
+ # clone, we rewrite these references so it keeps working.
919
+ for item in itertools.chain(
920
+ cls.__dict__.values(), additional_closure_functions_to_update
921
+ ):
922
+ if isinstance(item, (classmethod, staticmethod)):
923
+ # Class- and staticmethods hide their functions inside.
924
+ # These might need to be rewritten as well.
925
+ closure_cells = getattr(item.__func__, "__closure__", None)
926
+ elif isinstance(item, property):
927
+ # Workaround for property `super()` shortcut (PY3-only).
928
+ # There is no universal way for other descriptors.
929
+ closure_cells = getattr(item.fget, "__closure__", None)
930
+ else:
931
+ closure_cells = getattr(item, "__closure__", None)
932
+
933
+ if not closure_cells: # Catch None or the empty list.
934
+ continue
935
+ for cell in closure_cells:
936
+ try:
937
+ match = cell.cell_contents is self._cls
938
+ except ValueError: # noqa: PERF203
939
+ # ValueError: Cell is empty
940
+ pass
941
+ else:
942
+ if match:
943
+ cell.cell_contents = cls
944
+ return cls
945
+
946
+ def add_repr(self, ns):
947
+ self._cls_dict["__repr__"] = self._add_method_dunders(
948
+ _make_repr(self._attrs, ns, self._cls)
949
+ )
950
+ return self
951
+
952
+ def add_str(self):
953
+ repr = self._cls_dict.get("__repr__")
954
+ if repr is None:
955
+ msg = "__str__ can only be generated if a __repr__ exists."
956
+ raise ValueError(msg)
957
+
958
+ def __str__(self):
959
+ return self.__repr__()
960
+
961
+ self._cls_dict["__str__"] = self._add_method_dunders(__str__)
962
+ return self
963
+
964
+ def _make_getstate_setstate(self):
965
+ """
966
+ Create custom __setstate__ and __getstate__ methods.
967
+ """
968
+ # __weakref__ is not writable.
969
+ state_attr_names = tuple(
970
+ an for an in self._attr_names if an != "__weakref__"
971
+ )
972
+
973
+ def slots_getstate(self):
974
+ """
975
+ Automatically created by attrs.
976
+ """
977
+ return {name: getattr(self, name) for name in state_attr_names}
978
+
979
+ hash_caching_enabled = self._cache_hash
980
+
981
+ def slots_setstate(self, state):
982
+ """
983
+ Automatically created by attrs.
984
+ """
985
+ __bound_setattr = _OBJ_SETATTR.__get__(self)
986
+ if isinstance(state, tuple):
987
+ # Backward compatibility with attrs instances pickled with
988
+ # attrs versions before v22.2.0 which stored tuples.
989
+ for name, value in zip(state_attr_names, state):
990
+ __bound_setattr(name, value)
991
+ else:
992
+ for name in state_attr_names:
993
+ if name in state:
994
+ __bound_setattr(name, state[name])
995
+
996
+ # The hash code cache is not included when the object is
997
+ # serialized, but it still needs to be initialized to None to
998
+ # indicate that the first call to __hash__ should be a cache
999
+ # miss.
1000
+ if hash_caching_enabled:
1001
+ __bound_setattr(_HASH_CACHE_FIELD, None)
1002
+
1003
+ return slots_getstate, slots_setstate
1004
+
1005
+ def make_unhashable(self):
1006
+ self._cls_dict["__hash__"] = None
1007
+ return self
1008
+
1009
+ def add_hash(self):
1010
+ self._cls_dict["__hash__"] = self._add_method_dunders(
1011
+ _make_hash(
1012
+ self._cls,
1013
+ self._attrs,
1014
+ frozen=self._frozen,
1015
+ cache_hash=self._cache_hash,
1016
+ )
1017
+ )
1018
+
1019
+ return self
1020
+
1021
+ def add_init(self):
1022
+ self._cls_dict["__init__"] = self._add_method_dunders(
1023
+ _make_init(
1024
+ self._cls,
1025
+ self._attrs,
1026
+ self._has_pre_init,
1027
+ self._pre_init_has_args,
1028
+ self._has_post_init,
1029
+ self._frozen,
1030
+ self._slots,
1031
+ self._cache_hash,
1032
+ self._base_attr_map,
1033
+ self._is_exc,
1034
+ self._on_setattr,
1035
+ attrs_init=False,
1036
+ )
1037
+ )
1038
+
1039
+ return self
1040
+
1041
+ def add_replace(self):
1042
+ self._cls_dict["__replace__"] = self._add_method_dunders(
1043
+ lambda self, **changes: evolve(self, **changes)
1044
+ )
1045
+ return self
1046
+
1047
+ def add_match_args(self):
1048
+ self._cls_dict["__match_args__"] = tuple(
1049
+ field.name
1050
+ for field in self._attrs
1051
+ if field.init and not field.kw_only
1052
+ )
1053
+
1054
+ def add_attrs_init(self):
1055
+ self._cls_dict["__attrs_init__"] = self._add_method_dunders(
1056
+ _make_init(
1057
+ self._cls,
1058
+ self._attrs,
1059
+ self._has_pre_init,
1060
+ self._pre_init_has_args,
1061
+ self._has_post_init,
1062
+ self._frozen,
1063
+ self._slots,
1064
+ self._cache_hash,
1065
+ self._base_attr_map,
1066
+ self._is_exc,
1067
+ self._on_setattr,
1068
+ attrs_init=True,
1069
+ )
1070
+ )
1071
+
1072
+ return self
1073
+
1074
+ def add_eq(self):
1075
+ cd = self._cls_dict
1076
+
1077
+ cd["__eq__"] = self._add_method_dunders(
1078
+ _make_eq(self._cls, self._attrs)
1079
+ )
1080
+ cd["__ne__"] = self._add_method_dunders(_make_ne())
1081
+
1082
+ return self
1083
+
1084
+ def add_order(self):
1085
+ cd = self._cls_dict
1086
+
1087
+ cd["__lt__"], cd["__le__"], cd["__gt__"], cd["__ge__"] = (
1088
+ self._add_method_dunders(meth)
1089
+ for meth in _make_order(self._cls, self._attrs)
1090
+ )
1091
+
1092
+ return self
1093
+
1094
+ def add_setattr(self):
1095
+ if self._frozen:
1096
+ return self
1097
+
1098
+ sa_attrs = {}
1099
+ for a in self._attrs:
1100
+ on_setattr = a.on_setattr or self._on_setattr
1101
+ if on_setattr and on_setattr is not setters.NO_OP:
1102
+ sa_attrs[a.name] = a, on_setattr
1103
+
1104
+ if not sa_attrs:
1105
+ return self
1106
+
1107
+ if self._has_custom_setattr:
1108
+ # We need to write a __setattr__ but there already is one!
1109
+ msg = "Can't combine custom __setattr__ with on_setattr hooks."
1110
+ raise ValueError(msg)
1111
+
1112
+ # docstring comes from _add_method_dunders
1113
+ def __setattr__(self, name, val):
1114
+ try:
1115
+ a, hook = sa_attrs[name]
1116
+ except KeyError:
1117
+ nval = val
1118
+ else:
1119
+ nval = hook(self, a, val)
1120
+
1121
+ _OBJ_SETATTR(self, name, nval)
1122
+
1123
+ self._cls_dict["__attrs_own_setattr__"] = True
1124
+ self._cls_dict["__setattr__"] = self._add_method_dunders(__setattr__)
1125
+ self._wrote_own_setattr = True
1126
+
1127
+ return self
1128
+
1129
+ def _add_method_dunders(self, method):
1130
+ """
1131
+ Add __module__ and __qualname__ to a *method* if possible.
1132
+ """
1133
+ with contextlib.suppress(AttributeError):
1134
+ method.__module__ = self._cls.__module__
1135
+
1136
+ with contextlib.suppress(AttributeError):
1137
+ method.__qualname__ = f"{self._cls.__qualname__}.{method.__name__}"
1138
+
1139
+ with contextlib.suppress(AttributeError):
1140
+ method.__doc__ = (
1141
+ "Method generated by attrs for class "
1142
+ f"{self._cls.__qualname__}."
1143
+ )
1144
+
1145
+ return method
1146
+
1147
+
1148
+ def _determine_attrs_eq_order(cmp, eq, order, default_eq):
1149
+ """
1150
+ Validate the combination of *cmp*, *eq*, and *order*. Derive the effective
1151
+ values of eq and order. If *eq* is None, set it to *default_eq*.
1152
+ """
1153
+ if cmp is not None and any((eq is not None, order is not None)):
1154
+ msg = "Don't mix `cmp` with `eq' and `order`."
1155
+ raise ValueError(msg)
1156
+
1157
+ # cmp takes precedence due to bw-compatibility.
1158
+ if cmp is not None:
1159
+ return cmp, cmp
1160
+
1161
+ # If left None, equality is set to the specified default and ordering
1162
+ # mirrors equality.
1163
+ if eq is None:
1164
+ eq = default_eq
1165
+
1166
+ if order is None:
1167
+ order = eq
1168
+
1169
+ if eq is False and order is True:
1170
+ msg = "`order` can only be True if `eq` is True too."
1171
+ raise ValueError(msg)
1172
+
1173
+ return eq, order
1174
+
1175
+
1176
+ def _determine_attrib_eq_order(cmp, eq, order, default_eq):
1177
+ """
1178
+ Validate the combination of *cmp*, *eq*, and *order*. Derive the effective
1179
+ values of eq and order. If *eq* is None, set it to *default_eq*.
1180
+ """
1181
+ if cmp is not None and any((eq is not None, order is not None)):
1182
+ msg = "Don't mix `cmp` with `eq' and `order`."
1183
+ raise ValueError(msg)
1184
+
1185
+ def decide_callable_or_boolean(value):
1186
+ """
1187
+ Decide whether a key function is used.
1188
+ """
1189
+ if callable(value):
1190
+ value, key = True, value
1191
+ else:
1192
+ key = None
1193
+ return value, key
1194
+
1195
+ # cmp takes precedence due to bw-compatibility.
1196
+ if cmp is not None:
1197
+ cmp, cmp_key = decide_callable_or_boolean(cmp)
1198
+ return cmp, cmp_key, cmp, cmp_key
1199
+
1200
+ # If left None, equality is set to the specified default and ordering
1201
+ # mirrors equality.
1202
+ if eq is None:
1203
+ eq, eq_key = default_eq, None
1204
+ else:
1205
+ eq, eq_key = decide_callable_or_boolean(eq)
1206
+
1207
+ if order is None:
1208
+ order, order_key = eq, eq_key
1209
+ else:
1210
+ order, order_key = decide_callable_or_boolean(order)
1211
+
1212
+ if eq is False and order is True:
1213
+ msg = "`order` can only be True if `eq` is True too."
1214
+ raise ValueError(msg)
1215
+
1216
+ return eq, eq_key, order, order_key
1217
+
1218
+
1219
+ def _determine_whether_to_implement(
1220
+ cls, flag, auto_detect, dunders, default=True
1221
+ ):
1222
+ """
1223
+ Check whether we should implement a set of methods for *cls*.
1224
+
1225
+ *flag* is the argument passed into @attr.s like 'init', *auto_detect* the
1226
+ same as passed into @attr.s and *dunders* is a tuple of attribute names
1227
+ whose presence signal that the user has implemented it themselves.
1228
+
1229
+ Return *default* if no reason for either for or against is found.
1230
+ """
1231
+ if flag is True or flag is False:
1232
+ return flag
1233
+
1234
+ if flag is None and auto_detect is False:
1235
+ return default
1236
+
1237
+ # Logically, flag is None and auto_detect is True here.
1238
+ for dunder in dunders:
1239
+ if _has_own_attribute(cls, dunder):
1240
+ return False
1241
+
1242
+ return default
1243
+
1244
+
1245
+ def attrs(
1246
+ maybe_cls=None,
1247
+ these=None,
1248
+ repr_ns=None,
1249
+ repr=None,
1250
+ cmp=None,
1251
+ hash=None,
1252
+ init=None,
1253
+ slots=False,
1254
+ frozen=False,
1255
+ weakref_slot=True,
1256
+ str=False,
1257
+ auto_attribs=False,
1258
+ kw_only=False,
1259
+ cache_hash=False,
1260
+ auto_exc=False,
1261
+ eq=None,
1262
+ order=None,
1263
+ auto_detect=False,
1264
+ collect_by_mro=False,
1265
+ getstate_setstate=None,
1266
+ on_setattr=None,
1267
+ field_transformer=None,
1268
+ match_args=True,
1269
+ unsafe_hash=None,
1270
+ ):
1271
+ r"""
1272
+ A class decorator that adds :term:`dunder methods` according to the
1273
+ specified attributes using `attr.ib` or the *these* argument.
1274
+
1275
+ Consider using `attrs.define` / `attrs.frozen` in new code (``attr.s`` will
1276
+ *never* go away, though).
1277
+
1278
+ Args:
1279
+ repr_ns (str):
1280
+ When using nested classes, there was no way in Python 2 to
1281
+ automatically detect that. This argument allows to set a custom
1282
+ name for a more meaningful ``repr`` output. This argument is
1283
+ pointless in Python 3 and is therefore deprecated.
1284
+
1285
+ .. caution::
1286
+ Refer to `attrs.define` for the rest of the parameters, but note that they
1287
+ can have different defaults.
1288
+
1289
+ Notably, leaving *on_setattr* as `None` will **not** add any hooks.
1290
+
1291
+ .. versionadded:: 16.0.0 *slots*
1292
+ .. versionadded:: 16.1.0 *frozen*
1293
+ .. versionadded:: 16.3.0 *str*
1294
+ .. versionadded:: 16.3.0 Support for ``__attrs_post_init__``.
1295
+ .. versionchanged:: 17.1.0
1296
+ *hash* supports `None` as value which is also the default now.
1297
+ .. versionadded:: 17.3.0 *auto_attribs*
1298
+ .. versionchanged:: 18.1.0
1299
+ If *these* is passed, no attributes are deleted from the class body.
1300
+ .. versionchanged:: 18.1.0 If *these* is ordered, the order is retained.
1301
+ .. versionadded:: 18.2.0 *weakref_slot*
1302
+ .. deprecated:: 18.2.0
1303
+ ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now raise a
1304
+ `DeprecationWarning` if the classes compared are subclasses of
1305
+ each other. ``__eq`` and ``__ne__`` never tried to compared subclasses
1306
+ to each other.
1307
+ .. versionchanged:: 19.2.0
1308
+ ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now do not consider
1309
+ subclasses comparable anymore.
1310
+ .. versionadded:: 18.2.0 *kw_only*
1311
+ .. versionadded:: 18.2.0 *cache_hash*
1312
+ .. versionadded:: 19.1.0 *auto_exc*
1313
+ .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01.
1314
+ .. versionadded:: 19.2.0 *eq* and *order*
1315
+ .. versionadded:: 20.1.0 *auto_detect*
1316
+ .. versionadded:: 20.1.0 *collect_by_mro*
1317
+ .. versionadded:: 20.1.0 *getstate_setstate*
1318
+ .. versionadded:: 20.1.0 *on_setattr*
1319
+ .. versionadded:: 20.3.0 *field_transformer*
1320
+ .. versionchanged:: 21.1.0
1321
+ ``init=False`` injects ``__attrs_init__``
1322
+ .. versionchanged:: 21.1.0 Support for ``__attrs_pre_init__``
1323
+ .. versionchanged:: 21.1.0 *cmp* undeprecated
1324
+ .. versionadded:: 21.3.0 *match_args*
1325
+ .. versionadded:: 22.2.0
1326
+ *unsafe_hash* as an alias for *hash* (for :pep:`681` compliance).
1327
+ .. deprecated:: 24.1.0 *repr_ns*
1328
+ .. versionchanged:: 24.1.0
1329
+ Instances are not compared as tuples of attributes anymore, but using a
1330
+ big ``and`` condition. This is faster and has more correct behavior for
1331
+ uncomparable values like `math.nan`.
1332
+ .. versionadded:: 24.1.0
1333
+ If a class has an *inherited* classmethod called
1334
+ ``__attrs_init_subclass__``, it is executed after the class is created.
1335
+ .. deprecated:: 24.1.0 *hash* is deprecated in favor of *unsafe_hash*.
1336
+ """
1337
+ if repr_ns is not None:
1338
+ import warnings
1339
+
1340
+ warnings.warn(
1341
+ DeprecationWarning(
1342
+ "The `repr_ns` argument is deprecated and will be removed in or after August 2025."
1343
+ ),
1344
+ stacklevel=2,
1345
+ )
1346
+
1347
+ eq_, order_ = _determine_attrs_eq_order(cmp, eq, order, None)
1348
+
1349
+ # unsafe_hash takes precedence due to PEP 681.
1350
+ if unsafe_hash is not None:
1351
+ hash = unsafe_hash
1352
+
1353
+ if isinstance(on_setattr, (list, tuple)):
1354
+ on_setattr = setters.pipe(*on_setattr)
1355
+
1356
+ def wrap(cls):
1357
+ is_frozen = frozen or _has_frozen_base_class(cls)
1358
+ is_exc = auto_exc is True and issubclass(cls, BaseException)
1359
+ has_own_setattr = auto_detect and _has_own_attribute(
1360
+ cls, "__setattr__"
1361
+ )
1362
+
1363
+ if has_own_setattr and is_frozen:
1364
+ msg = "Can't freeze a class with a custom __setattr__."
1365
+ raise ValueError(msg)
1366
+
1367
+ builder = _ClassBuilder(
1368
+ cls,
1369
+ these,
1370
+ slots,
1371
+ is_frozen,
1372
+ weakref_slot,
1373
+ _determine_whether_to_implement(
1374
+ cls,
1375
+ getstate_setstate,
1376
+ auto_detect,
1377
+ ("__getstate__", "__setstate__"),
1378
+ default=slots,
1379
+ ),
1380
+ auto_attribs,
1381
+ kw_only,
1382
+ cache_hash,
1383
+ is_exc,
1384
+ collect_by_mro,
1385
+ on_setattr,
1386
+ has_own_setattr,
1387
+ field_transformer,
1388
+ )
1389
+ if _determine_whether_to_implement(
1390
+ cls, repr, auto_detect, ("__repr__",)
1391
+ ):
1392
+ builder.add_repr(repr_ns)
1393
+ if str is True:
1394
+ builder.add_str()
1395
+
1396
+ eq = _determine_whether_to_implement(
1397
+ cls, eq_, auto_detect, ("__eq__", "__ne__")
1398
+ )
1399
+ if not is_exc and eq is True:
1400
+ builder.add_eq()
1401
+ if not is_exc and _determine_whether_to_implement(
1402
+ cls, order_, auto_detect, ("__lt__", "__le__", "__gt__", "__ge__")
1403
+ ):
1404
+ builder.add_order()
1405
+
1406
+ builder.add_setattr()
1407
+
1408
+ nonlocal hash
1409
+ if (
1410
+ hash is None
1411
+ and auto_detect is True
1412
+ and _has_own_attribute(cls, "__hash__")
1413
+ ):
1414
+ hash = False
1415
+
1416
+ if hash is not True and hash is not False and hash is not None:
1417
+ # Can't use `hash in` because 1 == True for example.
1418
+ msg = "Invalid value for hash. Must be True, False, or None."
1419
+ raise TypeError(msg)
1420
+
1421
+ if hash is False or (hash is None and eq is False) or is_exc:
1422
+ # Don't do anything. Should fall back to __object__'s __hash__
1423
+ # which is by id.
1424
+ if cache_hash:
1425
+ msg = "Invalid value for cache_hash. To use hash caching, hashing must be either explicitly or implicitly enabled."
1426
+ raise TypeError(msg)
1427
+ elif hash is True or (
1428
+ hash is None and eq is True and is_frozen is True
1429
+ ):
1430
+ # Build a __hash__ if told so, or if it's safe.
1431
+ builder.add_hash()
1432
+ else:
1433
+ # Raise TypeError on attempts to hash.
1434
+ if cache_hash:
1435
+ msg = "Invalid value for cache_hash. To use hash caching, hashing must be either explicitly or implicitly enabled."
1436
+ raise TypeError(msg)
1437
+ builder.make_unhashable()
1438
+
1439
+ if _determine_whether_to_implement(
1440
+ cls, init, auto_detect, ("__init__",)
1441
+ ):
1442
+ builder.add_init()
1443
+ else:
1444
+ builder.add_attrs_init()
1445
+ if cache_hash:
1446
+ msg = "Invalid value for cache_hash. To use hash caching, init must be True."
1447
+ raise TypeError(msg)
1448
+
1449
+ if PY_3_13_PLUS and not _has_own_attribute(cls, "__replace__"):
1450
+ builder.add_replace()
1451
+
1452
+ if (
1453
+ PY_3_10_PLUS
1454
+ and match_args
1455
+ and not _has_own_attribute(cls, "__match_args__")
1456
+ ):
1457
+ builder.add_match_args()
1458
+
1459
+ return builder.build_class()
1460
+
1461
+ # maybe_cls's type depends on the usage of the decorator. It's a class
1462
+ # if it's used as `@attrs` but `None` if used as `@attrs()`.
1463
+ if maybe_cls is None:
1464
+ return wrap
1465
+
1466
+ return wrap(maybe_cls)
1467
+
1468
+
1469
+ _attrs = attrs
1470
+ """
1471
+ Internal alias so we can use it in functions that take an argument called
1472
+ *attrs*.
1473
+ """
1474
+
1475
+
1476
+ def _has_frozen_base_class(cls):
1477
+ """
1478
+ Check whether *cls* has a frozen ancestor by looking at its
1479
+ __setattr__.
1480
+ """
1481
+ return cls.__setattr__ is _frozen_setattrs
1482
+
1483
+
1484
+ def _generate_unique_filename(cls, func_name):
1485
+ """
1486
+ Create a "filename" suitable for a function being generated.
1487
+ """
1488
+ return (
1489
+ f"<attrs generated {func_name} {cls.__module__}."
1490
+ f"{getattr(cls, '__qualname__', cls.__name__)}>"
1491
+ )
1492
+
1493
+
1494
+ def _make_hash(cls, attrs, frozen, cache_hash):
1495
+ attrs = tuple(
1496
+ a for a in attrs if a.hash is True or (a.hash is None and a.eq is True)
1497
+ )
1498
+
1499
+ tab = " "
1500
+
1501
+ unique_filename = _generate_unique_filename(cls, "hash")
1502
+ type_hash = hash(unique_filename)
1503
+ # If eq is custom generated, we need to include the functions in globs
1504
+ globs = {}
1505
+
1506
+ hash_def = "def __hash__(self"
1507
+ hash_func = "hash(("
1508
+ closing_braces = "))"
1509
+ if not cache_hash:
1510
+ hash_def += "):"
1511
+ else:
1512
+ hash_def += ", *"
1513
+
1514
+ hash_def += ", _cache_wrapper=__import__('attr._make')._make._CacheHashWrapper):"
1515
+ hash_func = "_cache_wrapper(" + hash_func
1516
+ closing_braces += ")"
1517
+
1518
+ method_lines = [hash_def]
1519
+
1520
+ def append_hash_computation_lines(prefix, indent):
1521
+ """
1522
+ Generate the code for actually computing the hash code.
1523
+ Below this will either be returned directly or used to compute
1524
+ a value which is then cached, depending on the value of cache_hash
1525
+ """
1526
+
1527
+ method_lines.extend(
1528
+ [
1529
+ indent + prefix + hash_func,
1530
+ indent + f" {type_hash},",
1531
+ ]
1532
+ )
1533
+
1534
+ for a in attrs:
1535
+ if a.eq_key:
1536
+ cmp_name = f"_{a.name}_key"
1537
+ globs[cmp_name] = a.eq_key
1538
+ method_lines.append(
1539
+ indent + f" {cmp_name}(self.{a.name}),"
1540
+ )
1541
+ else:
1542
+ method_lines.append(indent + f" self.{a.name},")
1543
+
1544
+ method_lines.append(indent + " " + closing_braces)
1545
+
1546
+ if cache_hash:
1547
+ method_lines.append(tab + f"if self.{_HASH_CACHE_FIELD} is None:")
1548
+ if frozen:
1549
+ append_hash_computation_lines(
1550
+ f"object.__setattr__(self, '{_HASH_CACHE_FIELD}', ", tab * 2
1551
+ )
1552
+ method_lines.append(tab * 2 + ")") # close __setattr__
1553
+ else:
1554
+ append_hash_computation_lines(
1555
+ f"self.{_HASH_CACHE_FIELD} = ", tab * 2
1556
+ )
1557
+ method_lines.append(tab + f"return self.{_HASH_CACHE_FIELD}")
1558
+ else:
1559
+ append_hash_computation_lines("return ", tab)
1560
+
1561
+ script = "\n".join(method_lines)
1562
+ return _make_method("__hash__", script, unique_filename, globs)
1563
+
1564
+
1565
+ def _add_hash(cls, attrs):
1566
+ """
1567
+ Add a hash method to *cls*.
1568
+ """
1569
+ cls.__hash__ = _make_hash(cls, attrs, frozen=False, cache_hash=False)
1570
+ return cls
1571
+
1572
+
1573
+ def _make_ne():
1574
+ """
1575
+ Create __ne__ method.
1576
+ """
1577
+
1578
+ def __ne__(self, other):
1579
+ """
1580
+ Check equality and either forward a NotImplemented or
1581
+ return the result negated.
1582
+ """
1583
+ result = self.__eq__(other)
1584
+ if result is NotImplemented:
1585
+ return NotImplemented
1586
+
1587
+ return not result
1588
+
1589
+ return __ne__
1590
+
1591
+
1592
+ def _make_eq(cls, attrs):
1593
+ """
1594
+ Create __eq__ method for *cls* with *attrs*.
1595
+ """
1596
+ attrs = [a for a in attrs if a.eq]
1597
+
1598
+ unique_filename = _generate_unique_filename(cls, "eq")
1599
+ lines = [
1600
+ "def __eq__(self, other):",
1601
+ " if other.__class__ is not self.__class__:",
1602
+ " return NotImplemented",
1603
+ ]
1604
+
1605
+ globs = {}
1606
+ if attrs:
1607
+ lines.append(" return (")
1608
+ for a in attrs:
1609
+ if a.eq_key:
1610
+ cmp_name = f"_{a.name}_key"
1611
+ # Add the key function to the global namespace
1612
+ # of the evaluated function.
1613
+ globs[cmp_name] = a.eq_key
1614
+ lines.append(
1615
+ f" {cmp_name}(self.{a.name}) == {cmp_name}(other.{a.name})"
1616
+ )
1617
+ else:
1618
+ lines.append(f" self.{a.name} == other.{a.name}")
1619
+ if a is not attrs[-1]:
1620
+ lines[-1] = f"{lines[-1]} and"
1621
+ lines.append(" )")
1622
+ else:
1623
+ lines.append(" return True")
1624
+
1625
+ script = "\n".join(lines)
1626
+
1627
+ return _make_method("__eq__", script, unique_filename, globs)
1628
+
1629
+
1630
+ def _make_order(cls, attrs):
1631
+ """
1632
+ Create ordering methods for *cls* with *attrs*.
1633
+ """
1634
+ attrs = [a for a in attrs if a.order]
1635
+
1636
+ def attrs_to_tuple(obj):
1637
+ """
1638
+ Save us some typing.
1639
+ """
1640
+ return tuple(
1641
+ key(value) if key else value
1642
+ for value, key in (
1643
+ (getattr(obj, a.name), a.order_key) for a in attrs
1644
+ )
1645
+ )
1646
+
1647
+ def __lt__(self, other):
1648
+ """
1649
+ Automatically created by attrs.
1650
+ """
1651
+ if other.__class__ is self.__class__:
1652
+ return attrs_to_tuple(self) < attrs_to_tuple(other)
1653
+
1654
+ return NotImplemented
1655
+
1656
+ def __le__(self, other):
1657
+ """
1658
+ Automatically created by attrs.
1659
+ """
1660
+ if other.__class__ is self.__class__:
1661
+ return attrs_to_tuple(self) <= attrs_to_tuple(other)
1662
+
1663
+ return NotImplemented
1664
+
1665
+ def __gt__(self, other):
1666
+ """
1667
+ Automatically created by attrs.
1668
+ """
1669
+ if other.__class__ is self.__class__:
1670
+ return attrs_to_tuple(self) > attrs_to_tuple(other)
1671
+
1672
+ return NotImplemented
1673
+
1674
+ def __ge__(self, other):
1675
+ """
1676
+ Automatically created by attrs.
1677
+ """
1678
+ if other.__class__ is self.__class__:
1679
+ return attrs_to_tuple(self) >= attrs_to_tuple(other)
1680
+
1681
+ return NotImplemented
1682
+
1683
+ return __lt__, __le__, __gt__, __ge__
1684
+
1685
+
1686
+ def _add_eq(cls, attrs=None):
1687
+ """
1688
+ Add equality methods to *cls* with *attrs*.
1689
+ """
1690
+ if attrs is None:
1691
+ attrs = cls.__attrs_attrs__
1692
+
1693
+ cls.__eq__ = _make_eq(cls, attrs)
1694
+ cls.__ne__ = _make_ne()
1695
+
1696
+ return cls
1697
+
1698
+
1699
+ def _make_repr(attrs, ns, cls):
1700
+ unique_filename = _generate_unique_filename(cls, "repr")
1701
+ # Figure out which attributes to include, and which function to use to
1702
+ # format them. The a.repr value can be either bool or a custom
1703
+ # callable.
1704
+ attr_names_with_reprs = tuple(
1705
+ (a.name, (repr if a.repr is True else a.repr), a.init)
1706
+ for a in attrs
1707
+ if a.repr is not False
1708
+ )
1709
+ globs = {
1710
+ name + "_repr": r for name, r, _ in attr_names_with_reprs if r != repr
1711
+ }
1712
+ globs["_compat"] = _compat
1713
+ globs["AttributeError"] = AttributeError
1714
+ globs["NOTHING"] = NOTHING
1715
+ attribute_fragments = []
1716
+ for name, r, i in attr_names_with_reprs:
1717
+ accessor = (
1718
+ "self." + name if i else 'getattr(self, "' + name + '", NOTHING)'
1719
+ )
1720
+ fragment = (
1721
+ "%s={%s!r}" % (name, accessor)
1722
+ if r == repr
1723
+ else "%s={%s_repr(%s)}" % (name, name, accessor)
1724
+ )
1725
+ attribute_fragments.append(fragment)
1726
+ repr_fragment = ", ".join(attribute_fragments)
1727
+
1728
+ if ns is None:
1729
+ cls_name_fragment = '{self.__class__.__qualname__.rsplit(">.", 1)[-1]}'
1730
+ else:
1731
+ cls_name_fragment = ns + ".{self.__class__.__name__}"
1732
+
1733
+ lines = [
1734
+ "def __repr__(self):",
1735
+ " try:",
1736
+ " already_repring = _compat.repr_context.already_repring",
1737
+ " except AttributeError:",
1738
+ " already_repring = {id(self),}",
1739
+ " _compat.repr_context.already_repring = already_repring",
1740
+ " else:",
1741
+ " if id(self) in already_repring:",
1742
+ " return '...'",
1743
+ " else:",
1744
+ " already_repring.add(id(self))",
1745
+ " try:",
1746
+ f" return f'{cls_name_fragment}({repr_fragment})'",
1747
+ " finally:",
1748
+ " already_repring.remove(id(self))",
1749
+ ]
1750
+
1751
+ return _make_method(
1752
+ "__repr__", "\n".join(lines), unique_filename, globs=globs
1753
+ )
1754
+
1755
+
1756
+ def _add_repr(cls, ns=None, attrs=None):
1757
+ """
1758
+ Add a repr method to *cls*.
1759
+ """
1760
+ if attrs is None:
1761
+ attrs = cls.__attrs_attrs__
1762
+
1763
+ cls.__repr__ = _make_repr(attrs, ns, cls)
1764
+ return cls
1765
+
1766
+
1767
+ def fields(cls):
1768
+ """
1769
+ Return the tuple of *attrs* attributes for a class.
1770
+
1771
+ The tuple also allows accessing the fields by their names (see below for
1772
+ examples).
1773
+
1774
+ Args:
1775
+ cls (type): Class to introspect.
1776
+
1777
+ Raises:
1778
+ TypeError: If *cls* is not a class.
1779
+
1780
+ attrs.exceptions.NotAnAttrsClassError:
1781
+ If *cls* is not an *attrs* class.
1782
+
1783
+ Returns:
1784
+ tuple (with name accessors) of `attrs.Attribute`
1785
+
1786
+ .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields
1787
+ by name.
1788
+ .. versionchanged:: 23.1.0 Add support for generic classes.
1789
+ """
1790
+ generic_base = get_generic_base(cls)
1791
+
1792
+ if generic_base is None and not isinstance(cls, type):
1793
+ msg = "Passed object must be a class."
1794
+ raise TypeError(msg)
1795
+
1796
+ attrs = getattr(cls, "__attrs_attrs__", None)
1797
+
1798
+ if attrs is None:
1799
+ if generic_base is not None:
1800
+ attrs = getattr(generic_base, "__attrs_attrs__", None)
1801
+ if attrs is not None:
1802
+ # Even though this is global state, stick it on here to speed
1803
+ # it up. We rely on `cls` being cached for this to be
1804
+ # efficient.
1805
+ cls.__attrs_attrs__ = attrs
1806
+ return attrs
1807
+ msg = f"{cls!r} is not an attrs-decorated class."
1808
+ raise NotAnAttrsClassError(msg)
1809
+
1810
+ return attrs
1811
+
1812
+
1813
+ def fields_dict(cls):
1814
+ """
1815
+ Return an ordered dictionary of *attrs* attributes for a class, whose keys
1816
+ are the attribute names.
1817
+
1818
+ Args:
1819
+ cls (type): Class to introspect.
1820
+
1821
+ Raises:
1822
+ TypeError: If *cls* is not a class.
1823
+
1824
+ attrs.exceptions.NotAnAttrsClassError:
1825
+ If *cls* is not an *attrs* class.
1826
+
1827
+ Returns:
1828
+ dict[str, attrs.Attribute]: Dict of attribute name to definition
1829
+
1830
+ .. versionadded:: 18.1.0
1831
+ """
1832
+ if not isinstance(cls, type):
1833
+ msg = "Passed object must be a class."
1834
+ raise TypeError(msg)
1835
+ attrs = getattr(cls, "__attrs_attrs__", None)
1836
+ if attrs is None:
1837
+ msg = f"{cls!r} is not an attrs-decorated class."
1838
+ raise NotAnAttrsClassError(msg)
1839
+ return {a.name: a for a in attrs}
1840
+
1841
+
1842
+ def validate(inst):
1843
+ """
1844
+ Validate all attributes on *inst* that have a validator.
1845
+
1846
+ Leaves all exceptions through.
1847
+
1848
+ Args:
1849
+ inst: Instance of a class with *attrs* attributes.
1850
+ """
1851
+ if _config._run_validators is False:
1852
+ return
1853
+
1854
+ for a in fields(inst.__class__):
1855
+ v = a.validator
1856
+ if v is not None:
1857
+ v(inst, a, getattr(inst, a.name))
1858
+
1859
+
1860
+ def _is_slot_attr(a_name, base_attr_map):
1861
+ """
1862
+ Check if the attribute name comes from a slot class.
1863
+ """
1864
+ cls = base_attr_map.get(a_name)
1865
+ return cls and "__slots__" in cls.__dict__
1866
+
1867
+
1868
+ def _make_init(
1869
+ cls,
1870
+ attrs,
1871
+ pre_init,
1872
+ pre_init_has_args,
1873
+ post_init,
1874
+ frozen,
1875
+ slots,
1876
+ cache_hash,
1877
+ base_attr_map,
1878
+ is_exc,
1879
+ cls_on_setattr,
1880
+ attrs_init,
1881
+ ):
1882
+ has_cls_on_setattr = (
1883
+ cls_on_setattr is not None and cls_on_setattr is not setters.NO_OP
1884
+ )
1885
+
1886
+ if frozen and has_cls_on_setattr:
1887
+ msg = "Frozen classes can't use on_setattr."
1888
+ raise ValueError(msg)
1889
+
1890
+ needs_cached_setattr = cache_hash or frozen
1891
+ filtered_attrs = []
1892
+ attr_dict = {}
1893
+ for a in attrs:
1894
+ if not a.init and a.default is NOTHING:
1895
+ continue
1896
+
1897
+ filtered_attrs.append(a)
1898
+ attr_dict[a.name] = a
1899
+
1900
+ if a.on_setattr is not None:
1901
+ if frozen is True:
1902
+ msg = "Frozen classes can't use on_setattr."
1903
+ raise ValueError(msg)
1904
+
1905
+ needs_cached_setattr = True
1906
+ elif has_cls_on_setattr and a.on_setattr is not setters.NO_OP:
1907
+ needs_cached_setattr = True
1908
+
1909
+ unique_filename = _generate_unique_filename(cls, "init")
1910
+
1911
+ script, globs, annotations = _attrs_to_init_script(
1912
+ filtered_attrs,
1913
+ frozen,
1914
+ slots,
1915
+ pre_init,
1916
+ pre_init_has_args,
1917
+ post_init,
1918
+ cache_hash,
1919
+ base_attr_map,
1920
+ is_exc,
1921
+ needs_cached_setattr,
1922
+ has_cls_on_setattr,
1923
+ "__attrs_init__" if attrs_init else "__init__",
1924
+ )
1925
+ if cls.__module__ in sys.modules:
1926
+ # This makes typing.get_type_hints(CLS.__init__) resolve string types.
1927
+ globs.update(sys.modules[cls.__module__].__dict__)
1928
+
1929
+ globs.update({"NOTHING": NOTHING, "attr_dict": attr_dict})
1930
+
1931
+ if needs_cached_setattr:
1932
+ # Save the lookup overhead in __init__ if we need to circumvent
1933
+ # setattr hooks.
1934
+ globs["_cached_setattr_get"] = _OBJ_SETATTR.__get__
1935
+
1936
+ init = _make_method(
1937
+ "__attrs_init__" if attrs_init else "__init__",
1938
+ script,
1939
+ unique_filename,
1940
+ globs,
1941
+ )
1942
+ init.__annotations__ = annotations
1943
+
1944
+ return init
1945
+
1946
+
1947
+ def _setattr(attr_name: str, value_var: str, has_on_setattr: bool) -> str:
1948
+ """
1949
+ Use the cached object.setattr to set *attr_name* to *value_var*.
1950
+ """
1951
+ return f"_setattr('{attr_name}', {value_var})"
1952
+
1953
+
1954
+ def _setattr_with_converter(
1955
+ attr_name: str, value_var: str, has_on_setattr: bool, converter: Converter
1956
+ ) -> str:
1957
+ """
1958
+ Use the cached object.setattr to set *attr_name* to *value_var*, but run
1959
+ its converter first.
1960
+ """
1961
+ return f"_setattr('{attr_name}', {converter._fmt_converter_call(attr_name, value_var)})"
1962
+
1963
+
1964
+ def _assign(attr_name: str, value: str, has_on_setattr: bool) -> str:
1965
+ """
1966
+ Unless *attr_name* has an on_setattr hook, use normal assignment. Otherwise
1967
+ relegate to _setattr.
1968
+ """
1969
+ if has_on_setattr:
1970
+ return _setattr(attr_name, value, True)
1971
+
1972
+ return f"self.{attr_name} = {value}"
1973
+
1974
+
1975
+ def _assign_with_converter(
1976
+ attr_name: str, value_var: str, has_on_setattr: bool, converter: Converter
1977
+ ) -> str:
1978
+ """
1979
+ Unless *attr_name* has an on_setattr hook, use normal assignment after
1980
+ conversion. Otherwise relegate to _setattr_with_converter.
1981
+ """
1982
+ if has_on_setattr:
1983
+ return _setattr_with_converter(attr_name, value_var, True, converter)
1984
+
1985
+ return f"self.{attr_name} = {converter._fmt_converter_call(attr_name, value_var)}"
1986
+
1987
+
1988
+ def _determine_setters(
1989
+ frozen: bool, slots: bool, base_attr_map: dict[str, type]
1990
+ ):
1991
+ """
1992
+ Determine the correct setter functions based on whether a class is frozen
1993
+ and/or slotted.
1994
+ """
1995
+ if frozen is True:
1996
+ if slots is True:
1997
+ return (), _setattr, _setattr_with_converter
1998
+
1999
+ # Dict frozen classes assign directly to __dict__.
2000
+ # But only if the attribute doesn't come from an ancestor slot
2001
+ # class.
2002
+ # Note _inst_dict will be used again below if cache_hash is True
2003
+
2004
+ def fmt_setter(
2005
+ attr_name: str, value_var: str, has_on_setattr: bool
2006
+ ) -> str:
2007
+ if _is_slot_attr(attr_name, base_attr_map):
2008
+ return _setattr(attr_name, value_var, has_on_setattr)
2009
+
2010
+ return f"_inst_dict['{attr_name}'] = {value_var}"
2011
+
2012
+ def fmt_setter_with_converter(
2013
+ attr_name: str,
2014
+ value_var: str,
2015
+ has_on_setattr: bool,
2016
+ converter: Converter,
2017
+ ) -> str:
2018
+ if has_on_setattr or _is_slot_attr(attr_name, base_attr_map):
2019
+ return _setattr_with_converter(
2020
+ attr_name, value_var, has_on_setattr, converter
2021
+ )
2022
+
2023
+ return f"_inst_dict['{attr_name}'] = {converter._fmt_converter_call(attr_name, value_var)}"
2024
+
2025
+ return (
2026
+ ("_inst_dict = self.__dict__",),
2027
+ fmt_setter,
2028
+ fmt_setter_with_converter,
2029
+ )
2030
+
2031
+ # Not frozen -- we can just assign directly.
2032
+ return (), _assign, _assign_with_converter
2033
+
2034
+
2035
+ def _attrs_to_init_script(
2036
+ attrs: list[Attribute],
2037
+ is_frozen: bool,
2038
+ is_slotted: bool,
2039
+ call_pre_init: bool,
2040
+ pre_init_has_args: bool,
2041
+ call_post_init: bool,
2042
+ does_cache_hash: bool,
2043
+ base_attr_map: dict[str, type],
2044
+ is_exc: bool,
2045
+ needs_cached_setattr: bool,
2046
+ has_cls_on_setattr: bool,
2047
+ method_name: str,
2048
+ ) -> tuple[str, dict, dict]:
2049
+ """
2050
+ Return a script of an initializer for *attrs*, a dict of globals, and
2051
+ annotations for the initializer.
2052
+
2053
+ The globals are required by the generated script.
2054
+ """
2055
+ lines = ["self.__attrs_pre_init__()"] if call_pre_init else []
2056
+
2057
+ if needs_cached_setattr:
2058
+ lines.append(
2059
+ # Circumvent the __setattr__ descriptor to save one lookup per
2060
+ # assignment. Note _setattr will be used again below if
2061
+ # does_cache_hash is True.
2062
+ "_setattr = _cached_setattr_get(self)"
2063
+ )
2064
+
2065
+ extra_lines, fmt_setter, fmt_setter_with_converter = _determine_setters(
2066
+ is_frozen, is_slotted, base_attr_map
2067
+ )
2068
+ lines.extend(extra_lines)
2069
+
2070
+ args = []
2071
+ kw_only_args = []
2072
+ attrs_to_validate = []
2073
+
2074
+ # This is a dictionary of names to validator and converter callables.
2075
+ # Injecting this into __init__ globals lets us avoid lookups.
2076
+ names_for_globals = {}
2077
+ annotations = {"return": None}
2078
+
2079
+ for a in attrs:
2080
+ if a.validator:
2081
+ attrs_to_validate.append(a)
2082
+
2083
+ attr_name = a.name
2084
+ has_on_setattr = a.on_setattr is not None or (
2085
+ a.on_setattr is not setters.NO_OP and has_cls_on_setattr
2086
+ )
2087
+ # a.alias is set to maybe-mangled attr_name in _ClassBuilder if not
2088
+ # explicitly provided
2089
+ arg_name = a.alias
2090
+
2091
+ has_factory = isinstance(a.default, Factory)
2092
+ maybe_self = "self" if has_factory and a.default.takes_self else ""
2093
+
2094
+ if a.converter is not None and not isinstance(a.converter, Converter):
2095
+ converter = Converter(a.converter)
2096
+ else:
2097
+ converter = a.converter
2098
+
2099
+ if a.init is False:
2100
+ if has_factory:
2101
+ init_factory_name = _INIT_FACTORY_PAT % (a.name,)
2102
+ if converter is not None:
2103
+ lines.append(
2104
+ fmt_setter_with_converter(
2105
+ attr_name,
2106
+ init_factory_name + f"({maybe_self})",
2107
+ has_on_setattr,
2108
+ converter,
2109
+ )
2110
+ )
2111
+ names_for_globals[converter._get_global_name(a.name)] = (
2112
+ converter.converter
2113
+ )
2114
+ else:
2115
+ lines.append(
2116
+ fmt_setter(
2117
+ attr_name,
2118
+ init_factory_name + f"({maybe_self})",
2119
+ has_on_setattr,
2120
+ )
2121
+ )
2122
+ names_for_globals[init_factory_name] = a.default.factory
2123
+ elif converter is not None:
2124
+ lines.append(
2125
+ fmt_setter_with_converter(
2126
+ attr_name,
2127
+ f"attr_dict['{attr_name}'].default",
2128
+ has_on_setattr,
2129
+ converter,
2130
+ )
2131
+ )
2132
+ names_for_globals[converter._get_global_name(a.name)] = (
2133
+ converter.converter
2134
+ )
2135
+ else:
2136
+ lines.append(
2137
+ fmt_setter(
2138
+ attr_name,
2139
+ f"attr_dict['{attr_name}'].default",
2140
+ has_on_setattr,
2141
+ )
2142
+ )
2143
+ elif a.default is not NOTHING and not has_factory:
2144
+ arg = f"{arg_name}=attr_dict['{attr_name}'].default"
2145
+ if a.kw_only:
2146
+ kw_only_args.append(arg)
2147
+ else:
2148
+ args.append(arg)
2149
+
2150
+ if converter is not None:
2151
+ lines.append(
2152
+ fmt_setter_with_converter(
2153
+ attr_name, arg_name, has_on_setattr, converter
2154
+ )
2155
+ )
2156
+ names_for_globals[converter._get_global_name(a.name)] = (
2157
+ converter.converter
2158
+ )
2159
+ else:
2160
+ lines.append(fmt_setter(attr_name, arg_name, has_on_setattr))
2161
+
2162
+ elif has_factory:
2163
+ arg = f"{arg_name}=NOTHING"
2164
+ if a.kw_only:
2165
+ kw_only_args.append(arg)
2166
+ else:
2167
+ args.append(arg)
2168
+ lines.append(f"if {arg_name} is not NOTHING:")
2169
+
2170
+ init_factory_name = _INIT_FACTORY_PAT % (a.name,)
2171
+ if converter is not None:
2172
+ lines.append(
2173
+ " "
2174
+ + fmt_setter_with_converter(
2175
+ attr_name, arg_name, has_on_setattr, converter
2176
+ )
2177
+ )
2178
+ lines.append("else:")
2179
+ lines.append(
2180
+ " "
2181
+ + fmt_setter_with_converter(
2182
+ attr_name,
2183
+ init_factory_name + "(" + maybe_self + ")",
2184
+ has_on_setattr,
2185
+ converter,
2186
+ )
2187
+ )
2188
+ names_for_globals[converter._get_global_name(a.name)] = (
2189
+ converter.converter
2190
+ )
2191
+ else:
2192
+ lines.append(
2193
+ " " + fmt_setter(attr_name, arg_name, has_on_setattr)
2194
+ )
2195
+ lines.append("else:")
2196
+ lines.append(
2197
+ " "
2198
+ + fmt_setter(
2199
+ attr_name,
2200
+ init_factory_name + "(" + maybe_self + ")",
2201
+ has_on_setattr,
2202
+ )
2203
+ )
2204
+ names_for_globals[init_factory_name] = a.default.factory
2205
+ else:
2206
+ if a.kw_only:
2207
+ kw_only_args.append(arg_name)
2208
+ else:
2209
+ args.append(arg_name)
2210
+
2211
+ if converter is not None:
2212
+ lines.append(
2213
+ fmt_setter_with_converter(
2214
+ attr_name, arg_name, has_on_setattr, converter
2215
+ )
2216
+ )
2217
+ names_for_globals[converter._get_global_name(a.name)] = (
2218
+ converter.converter
2219
+ )
2220
+ else:
2221
+ lines.append(fmt_setter(attr_name, arg_name, has_on_setattr))
2222
+
2223
+ if a.init is True:
2224
+ if a.type is not None and converter is None:
2225
+ annotations[arg_name] = a.type
2226
+ elif converter is not None and converter._first_param_type:
2227
+ # Use the type from the converter if present.
2228
+ annotations[arg_name] = converter._first_param_type
2229
+
2230
+ if attrs_to_validate: # we can skip this if there are no validators.
2231
+ names_for_globals["_config"] = _config
2232
+ lines.append("if _config._run_validators is True:")
2233
+ for a in attrs_to_validate:
2234
+ val_name = "__attr_validator_" + a.name
2235
+ attr_name = "__attr_" + a.name
2236
+ lines.append(f" {val_name}(self, {attr_name}, self.{a.name})")
2237
+ names_for_globals[val_name] = a.validator
2238
+ names_for_globals[attr_name] = a
2239
+
2240
+ if call_post_init:
2241
+ lines.append("self.__attrs_post_init__()")
2242
+
2243
+ # Because this is set only after __attrs_post_init__ is called, a crash
2244
+ # will result if post-init tries to access the hash code. This seemed
2245
+ # preferable to setting this beforehand, in which case alteration to field
2246
+ # values during post-init combined with post-init accessing the hash code
2247
+ # would result in silent bugs.
2248
+ if does_cache_hash:
2249
+ if is_frozen:
2250
+ if is_slotted:
2251
+ init_hash_cache = f"_setattr('{_HASH_CACHE_FIELD}', None)"
2252
+ else:
2253
+ init_hash_cache = f"_inst_dict['{_HASH_CACHE_FIELD}'] = None"
2254
+ else:
2255
+ init_hash_cache = f"self.{_HASH_CACHE_FIELD} = None"
2256
+ lines.append(init_hash_cache)
2257
+
2258
+ # For exceptions we rely on BaseException.__init__ for proper
2259
+ # initialization.
2260
+ if is_exc:
2261
+ vals = ",".join(f"self.{a.name}" for a in attrs if a.init)
2262
+
2263
+ lines.append(f"BaseException.__init__(self, {vals})")
2264
+
2265
+ args = ", ".join(args)
2266
+ pre_init_args = args
2267
+ if kw_only_args:
2268
+ # leading comma & kw_only args
2269
+ args += f"{', ' if args else ''}*, {', '.join(kw_only_args)}"
2270
+ pre_init_kw_only_args = ", ".join(
2271
+ [
2272
+ f"{kw_arg_name}={kw_arg_name}"
2273
+ # We need to remove the defaults from the kw_only_args.
2274
+ for kw_arg_name in (kwa.split("=")[0] for kwa in kw_only_args)
2275
+ ]
2276
+ )
2277
+ pre_init_args += ", " if pre_init_args else ""
2278
+ pre_init_args += pre_init_kw_only_args
2279
+
2280
+ if call_pre_init and pre_init_has_args:
2281
+ # If pre init method has arguments, pass same arguments as `__init__`.
2282
+ lines[0] = f"self.__attrs_pre_init__({pre_init_args})"
2283
+
2284
+ # Python <3.12 doesn't allow backslashes in f-strings.
2285
+ NL = "\n "
2286
+ return (
2287
+ f"""def {method_name}(self, {args}):
2288
+ {NL.join(lines) if lines else 'pass'}
2289
+ """,
2290
+ names_for_globals,
2291
+ annotations,
2292
+ )
2293
+
2294
+
2295
+ def _default_init_alias_for(name: str) -> str:
2296
+ """
2297
+ The default __init__ parameter name for a field.
2298
+
2299
+ This performs private-name adjustment via leading-unscore stripping,
2300
+ and is the default value of Attribute.alias if not provided.
2301
+ """
2302
+
2303
+ return name.lstrip("_")
2304
+
2305
+
2306
+ class Attribute:
2307
+ """
2308
+ *Read-only* representation of an attribute.
2309
+
2310
+ .. warning::
2311
+
2312
+ You should never instantiate this class yourself.
2313
+
2314
+ The class has *all* arguments of `attr.ib` (except for ``factory`` which is
2315
+ only syntactic sugar for ``default=Factory(...)`` plus the following:
2316
+
2317
+ - ``name`` (`str`): The name of the attribute.
2318
+ - ``alias`` (`str`): The __init__ parameter name of the attribute, after
2319
+ any explicit overrides and default private-attribute-name handling.
2320
+ - ``inherited`` (`bool`): Whether or not that attribute has been inherited
2321
+ from a base class.
2322
+ - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The
2323
+ callables that are used for comparing and ordering objects by this
2324
+ attribute, respectively. These are set by passing a callable to
2325
+ `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also
2326
+ :ref:`comparison customization <custom-comparison>`.
2327
+
2328
+ Instances of this class are frequently used for introspection purposes
2329
+ like:
2330
+
2331
+ - `fields` returns a tuple of them.
2332
+ - Validators get them passed as the first argument.
2333
+ - The :ref:`field transformer <transform-fields>` hook receives a list of
2334
+ them.
2335
+ - The ``alias`` property exposes the __init__ parameter name of the field,
2336
+ with any overrides and default private-attribute handling applied.
2337
+
2338
+
2339
+ .. versionadded:: 20.1.0 *inherited*
2340
+ .. versionadded:: 20.1.0 *on_setattr*
2341
+ .. versionchanged:: 20.2.0 *inherited* is not taken into account for
2342
+ equality checks and hashing anymore.
2343
+ .. versionadded:: 21.1.0 *eq_key* and *order_key*
2344
+ .. versionadded:: 22.2.0 *alias*
2345
+
2346
+ For the full version history of the fields, see `attr.ib`.
2347
+ """
2348
+
2349
+ # These slots must NOT be reordered because we use them later for
2350
+ # instantiation.
2351
+ __slots__ = ( # noqa: RUF023
2352
+ "name",
2353
+ "default",
2354
+ "validator",
2355
+ "repr",
2356
+ "eq",
2357
+ "eq_key",
2358
+ "order",
2359
+ "order_key",
2360
+ "hash",
2361
+ "init",
2362
+ "metadata",
2363
+ "type",
2364
+ "converter",
2365
+ "kw_only",
2366
+ "inherited",
2367
+ "on_setattr",
2368
+ "alias",
2369
+ )
2370
+
2371
+ def __init__(
2372
+ self,
2373
+ name,
2374
+ default,
2375
+ validator,
2376
+ repr,
2377
+ cmp, # XXX: unused, remove along with other cmp code.
2378
+ hash,
2379
+ init,
2380
+ inherited,
2381
+ metadata=None,
2382
+ type=None,
2383
+ converter=None,
2384
+ kw_only=False,
2385
+ eq=None,
2386
+ eq_key=None,
2387
+ order=None,
2388
+ order_key=None,
2389
+ on_setattr=None,
2390
+ alias=None,
2391
+ ):
2392
+ eq, eq_key, order, order_key = _determine_attrib_eq_order(
2393
+ cmp, eq_key or eq, order_key or order, True
2394
+ )
2395
+
2396
+ # Cache this descriptor here to speed things up later.
2397
+ bound_setattr = _OBJ_SETATTR.__get__(self)
2398
+
2399
+ # Despite the big red warning, people *do* instantiate `Attribute`
2400
+ # themselves.
2401
+ bound_setattr("name", name)
2402
+ bound_setattr("default", default)
2403
+ bound_setattr("validator", validator)
2404
+ bound_setattr("repr", repr)
2405
+ bound_setattr("eq", eq)
2406
+ bound_setattr("eq_key", eq_key)
2407
+ bound_setattr("order", order)
2408
+ bound_setattr("order_key", order_key)
2409
+ bound_setattr("hash", hash)
2410
+ bound_setattr("init", init)
2411
+ bound_setattr("converter", converter)
2412
+ bound_setattr(
2413
+ "metadata",
2414
+ (
2415
+ types.MappingProxyType(dict(metadata)) # Shallow copy
2416
+ if metadata
2417
+ else _EMPTY_METADATA_SINGLETON
2418
+ ),
2419
+ )
2420
+ bound_setattr("type", type)
2421
+ bound_setattr("kw_only", kw_only)
2422
+ bound_setattr("inherited", inherited)
2423
+ bound_setattr("on_setattr", on_setattr)
2424
+ bound_setattr("alias", alias)
2425
+
2426
+ def __setattr__(self, name, value):
2427
+ raise FrozenInstanceError
2428
+
2429
+ @classmethod
2430
+ def from_counting_attr(cls, name, ca, type=None):
2431
+ # type holds the annotated value. deal with conflicts:
2432
+ if type is None:
2433
+ type = ca.type
2434
+ elif ca.type is not None:
2435
+ msg = "Type annotation and type argument cannot both be present"
2436
+ raise ValueError(msg)
2437
+ inst_dict = {
2438
+ k: getattr(ca, k)
2439
+ for k in Attribute.__slots__
2440
+ if k
2441
+ not in (
2442
+ "name",
2443
+ "validator",
2444
+ "default",
2445
+ "type",
2446
+ "inherited",
2447
+ ) # exclude methods and deprecated alias
2448
+ }
2449
+ return cls(
2450
+ name=name,
2451
+ validator=ca._validator,
2452
+ default=ca._default,
2453
+ type=type,
2454
+ cmp=None,
2455
+ inherited=False,
2456
+ **inst_dict,
2457
+ )
2458
+
2459
+ # Don't use attrs.evolve since fields(Attribute) doesn't work
2460
+ def evolve(self, **changes):
2461
+ """
2462
+ Copy *self* and apply *changes*.
2463
+
2464
+ This works similarly to `attrs.evolve` but that function does not work
2465
+ with :class:`attrs.Attribute`.
2466
+
2467
+ It is mainly meant to be used for `transform-fields`.
2468
+
2469
+ .. versionadded:: 20.3.0
2470
+ """
2471
+ new = copy.copy(self)
2472
+
2473
+ new._setattrs(changes.items())
2474
+
2475
+ return new
2476
+
2477
+ # Don't use _add_pickle since fields(Attribute) doesn't work
2478
+ def __getstate__(self):
2479
+ """
2480
+ Play nice with pickle.
2481
+ """
2482
+ return tuple(
2483
+ getattr(self, name) if name != "metadata" else dict(self.metadata)
2484
+ for name in self.__slots__
2485
+ )
2486
+
2487
+ def __setstate__(self, state):
2488
+ """
2489
+ Play nice with pickle.
2490
+ """
2491
+ self._setattrs(zip(self.__slots__, state))
2492
+
2493
+ def _setattrs(self, name_values_pairs):
2494
+ bound_setattr = _OBJ_SETATTR.__get__(self)
2495
+ for name, value in name_values_pairs:
2496
+ if name != "metadata":
2497
+ bound_setattr(name, value)
2498
+ else:
2499
+ bound_setattr(
2500
+ name,
2501
+ (
2502
+ types.MappingProxyType(dict(value))
2503
+ if value
2504
+ else _EMPTY_METADATA_SINGLETON
2505
+ ),
2506
+ )
2507
+
2508
+
2509
+ _a = [
2510
+ Attribute(
2511
+ name=name,
2512
+ default=NOTHING,
2513
+ validator=None,
2514
+ repr=True,
2515
+ cmp=None,
2516
+ eq=True,
2517
+ order=False,
2518
+ hash=(name != "metadata"),
2519
+ init=True,
2520
+ inherited=False,
2521
+ alias=_default_init_alias_for(name),
2522
+ )
2523
+ for name in Attribute.__slots__
2524
+ ]
2525
+
2526
+ Attribute = _add_hash(
2527
+ _add_eq(
2528
+ _add_repr(Attribute, attrs=_a),
2529
+ attrs=[a for a in _a if a.name != "inherited"],
2530
+ ),
2531
+ attrs=[a for a in _a if a.hash and a.name != "inherited"],
2532
+ )
2533
+
2534
+
2535
+ class _CountingAttr:
2536
+ """
2537
+ Intermediate representation of attributes that uses a counter to preserve
2538
+ the order in which the attributes have been defined.
2539
+
2540
+ *Internal* data structure of the attrs library. Running into is most
2541
+ likely the result of a bug like a forgotten `@attr.s` decorator.
2542
+ """
2543
+
2544
+ __slots__ = (
2545
+ "_default",
2546
+ "_validator",
2547
+ "alias",
2548
+ "converter",
2549
+ "counter",
2550
+ "eq",
2551
+ "eq_key",
2552
+ "hash",
2553
+ "init",
2554
+ "kw_only",
2555
+ "metadata",
2556
+ "on_setattr",
2557
+ "order",
2558
+ "order_key",
2559
+ "repr",
2560
+ "type",
2561
+ )
2562
+ __attrs_attrs__ = (
2563
+ *tuple(
2564
+ Attribute(
2565
+ name=name,
2566
+ alias=_default_init_alias_for(name),
2567
+ default=NOTHING,
2568
+ validator=None,
2569
+ repr=True,
2570
+ cmp=None,
2571
+ hash=True,
2572
+ init=True,
2573
+ kw_only=False,
2574
+ eq=True,
2575
+ eq_key=None,
2576
+ order=False,
2577
+ order_key=None,
2578
+ inherited=False,
2579
+ on_setattr=None,
2580
+ )
2581
+ for name in (
2582
+ "counter",
2583
+ "_default",
2584
+ "repr",
2585
+ "eq",
2586
+ "order",
2587
+ "hash",
2588
+ "init",
2589
+ "on_setattr",
2590
+ "alias",
2591
+ )
2592
+ ),
2593
+ Attribute(
2594
+ name="metadata",
2595
+ alias="metadata",
2596
+ default=None,
2597
+ validator=None,
2598
+ repr=True,
2599
+ cmp=None,
2600
+ hash=False,
2601
+ init=True,
2602
+ kw_only=False,
2603
+ eq=True,
2604
+ eq_key=None,
2605
+ order=False,
2606
+ order_key=None,
2607
+ inherited=False,
2608
+ on_setattr=None,
2609
+ ),
2610
+ )
2611
+ cls_counter = 0
2612
+
2613
+ def __init__(
2614
+ self,
2615
+ default,
2616
+ validator,
2617
+ repr,
2618
+ cmp,
2619
+ hash,
2620
+ init,
2621
+ converter,
2622
+ metadata,
2623
+ type,
2624
+ kw_only,
2625
+ eq,
2626
+ eq_key,
2627
+ order,
2628
+ order_key,
2629
+ on_setattr,
2630
+ alias,
2631
+ ):
2632
+ _CountingAttr.cls_counter += 1
2633
+ self.counter = _CountingAttr.cls_counter
2634
+ self._default = default
2635
+ self._validator = validator
2636
+ self.converter = converter
2637
+ self.repr = repr
2638
+ self.eq = eq
2639
+ self.eq_key = eq_key
2640
+ self.order = order
2641
+ self.order_key = order_key
2642
+ self.hash = hash
2643
+ self.init = init
2644
+ self.metadata = metadata
2645
+ self.type = type
2646
+ self.kw_only = kw_only
2647
+ self.on_setattr = on_setattr
2648
+ self.alias = alias
2649
+
2650
+ def validator(self, meth):
2651
+ """
2652
+ Decorator that adds *meth* to the list of validators.
2653
+
2654
+ Returns *meth* unchanged.
2655
+
2656
+ .. versionadded:: 17.1.0
2657
+ """
2658
+ if self._validator is None:
2659
+ self._validator = meth
2660
+ else:
2661
+ self._validator = and_(self._validator, meth)
2662
+ return meth
2663
+
2664
+ def default(self, meth):
2665
+ """
2666
+ Decorator that allows to set the default for an attribute.
2667
+
2668
+ Returns *meth* unchanged.
2669
+
2670
+ Raises:
2671
+ DefaultAlreadySetError: If default has been set before.
2672
+
2673
+ .. versionadded:: 17.1.0
2674
+ """
2675
+ if self._default is not NOTHING:
2676
+ raise DefaultAlreadySetError
2677
+
2678
+ self._default = Factory(meth, takes_self=True)
2679
+
2680
+ return meth
2681
+
2682
+
2683
+ _CountingAttr = _add_eq(_add_repr(_CountingAttr))
2684
+
2685
+
2686
+ class Factory:
2687
+ """
2688
+ Stores a factory callable.
2689
+
2690
+ If passed as the default value to `attrs.field`, the factory is used to
2691
+ generate a new value.
2692
+
2693
+ Args:
2694
+ factory (typing.Callable):
2695
+ A callable that takes either none or exactly one mandatory
2696
+ positional argument depending on *takes_self*.
2697
+
2698
+ takes_self (bool):
2699
+ Pass the partially initialized instance that is being initialized
2700
+ as a positional argument.
2701
+
2702
+ .. versionadded:: 17.1.0 *takes_self*
2703
+ """
2704
+
2705
+ __slots__ = ("factory", "takes_self")
2706
+
2707
+ def __init__(self, factory, takes_self=False):
2708
+ self.factory = factory
2709
+ self.takes_self = takes_self
2710
+
2711
+ def __getstate__(self):
2712
+ """
2713
+ Play nice with pickle.
2714
+ """
2715
+ return tuple(getattr(self, name) for name in self.__slots__)
2716
+
2717
+ def __setstate__(self, state):
2718
+ """
2719
+ Play nice with pickle.
2720
+ """
2721
+ for name, value in zip(self.__slots__, state):
2722
+ setattr(self, name, value)
2723
+
2724
+
2725
+ _f = [
2726
+ Attribute(
2727
+ name=name,
2728
+ default=NOTHING,
2729
+ validator=None,
2730
+ repr=True,
2731
+ cmp=None,
2732
+ eq=True,
2733
+ order=False,
2734
+ hash=True,
2735
+ init=True,
2736
+ inherited=False,
2737
+ )
2738
+ for name in Factory.__slots__
2739
+ ]
2740
+
2741
+ Factory = _add_hash(_add_eq(_add_repr(Factory, attrs=_f), attrs=_f), attrs=_f)
2742
+
2743
+
2744
+ class Converter:
2745
+ """
2746
+ Stores a converter callable.
2747
+
2748
+ Allows for the wrapped converter to take additional arguments. The
2749
+ arguments are passed in the order they are documented.
2750
+
2751
+ Args:
2752
+ converter (Callable): A callable that converts the passed value.
2753
+
2754
+ takes_self (bool):
2755
+ Pass the partially initialized instance that is being initialized
2756
+ as a positional argument. (default: `False`)
2757
+
2758
+ takes_field (bool):
2759
+ Pass the field definition (an :class:`Attribute`) into the
2760
+ converter as a positional argument. (default: `False`)
2761
+
2762
+ .. versionadded:: 24.1.0
2763
+ """
2764
+
2765
+ __slots__ = (
2766
+ "__call__",
2767
+ "_first_param_type",
2768
+ "_global_name",
2769
+ "converter",
2770
+ "takes_field",
2771
+ "takes_self",
2772
+ )
2773
+
2774
+ def __init__(self, converter, *, takes_self=False, takes_field=False):
2775
+ self.converter = converter
2776
+ self.takes_self = takes_self
2777
+ self.takes_field = takes_field
2778
+
2779
+ ex = _AnnotationExtractor(converter)
2780
+ self._first_param_type = ex.get_first_param_type()
2781
+
2782
+ if not (self.takes_self or self.takes_field):
2783
+ self.__call__ = lambda value, _, __: self.converter(value)
2784
+ elif self.takes_self and not self.takes_field:
2785
+ self.__call__ = lambda value, instance, __: self.converter(
2786
+ value, instance
2787
+ )
2788
+ elif not self.takes_self and self.takes_field:
2789
+ self.__call__ = lambda value, __, field: self.converter(
2790
+ value, field
2791
+ )
2792
+ else:
2793
+ self.__call__ = lambda value, instance, field: self.converter(
2794
+ value, instance, field
2795
+ )
2796
+
2797
+ rt = ex.get_return_type()
2798
+ if rt is not None:
2799
+ self.__call__.__annotations__["return"] = rt
2800
+
2801
+ @staticmethod
2802
+ def _get_global_name(attr_name: str) -> str:
2803
+ """
2804
+ Return the name that a converter for an attribute name *attr_name*
2805
+ would have.
2806
+ """
2807
+ return f"__attr_converter_{attr_name}"
2808
+
2809
+ def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:
2810
+ """
2811
+ Return a string that calls the converter for an attribute name
2812
+ *attr_name* and the value in variable named *value_var* according to
2813
+ `self.takes_self` and `self.takes_field`.
2814
+ """
2815
+ if not (self.takes_self or self.takes_field):
2816
+ return f"{self._get_global_name(attr_name)}({value_var})"
2817
+
2818
+ if self.takes_self and self.takes_field:
2819
+ return f"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])"
2820
+
2821
+ if self.takes_self:
2822
+ return f"{self._get_global_name(attr_name)}({value_var}, self)"
2823
+
2824
+ return f"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])"
2825
+
2826
+ def __getstate__(self):
2827
+ """
2828
+ Return a dict containing only converter and takes_self -- the rest gets
2829
+ computed when loading.
2830
+ """
2831
+ return {
2832
+ "converter": self.converter,
2833
+ "takes_self": self.takes_self,
2834
+ "takes_field": self.takes_field,
2835
+ }
2836
+
2837
+ def __setstate__(self, state):
2838
+ """
2839
+ Load instance from state.
2840
+ """
2841
+ self.__init__(**state)
2842
+
2843
+
2844
+ _f = [
2845
+ Attribute(
2846
+ name=name,
2847
+ default=NOTHING,
2848
+ validator=None,
2849
+ repr=True,
2850
+ cmp=None,
2851
+ eq=True,
2852
+ order=False,
2853
+ hash=True,
2854
+ init=True,
2855
+ inherited=False,
2856
+ )
2857
+ for name in ("converter", "takes_self", "takes_field")
2858
+ ]
2859
+
2860
+ Converter = _add_hash(
2861
+ _add_eq(_add_repr(Converter, attrs=_f), attrs=_f), attrs=_f
2862
+ )
2863
+
2864
+
2865
+ def make_class(
2866
+ name, attrs, bases=(object,), class_body=None, **attributes_arguments
2867
+ ):
2868
+ r"""
2869
+ A quick way to create a new class called *name* with *attrs*.
2870
+
2871
+ .. note::
2872
+
2873
+ ``make_class()`` is a thin wrapper around `attr.s`, not `attrs.define`
2874
+ which means that it doesn't come with some of the improved defaults.
2875
+
2876
+ For example, if you want the same ``on_setattr`` behavior as in
2877
+ `attrs.define`, you have to pass the hooks yourself: ``make_class(...,
2878
+ on_setattr=setters.pipe(setters.convert, setters.validate)``
2879
+
2880
+ Args:
2881
+ name (str): The name for the new class.
2882
+
2883
+ attrs (list | dict):
2884
+ A list of names or a dictionary of mappings of names to `attr.ib`\
2885
+ s / `attrs.field`\ s.
2886
+
2887
+ The order is deduced from the order of the names or attributes
2888
+ inside *attrs*. Otherwise the order of the definition of the
2889
+ attributes is used.
2890
+
2891
+ bases (tuple[type, ...]): Classes that the new class will subclass.
2892
+
2893
+ class_body (dict):
2894
+ An optional dictionary of class attributes for the new class.
2895
+
2896
+ attributes_arguments: Passed unmodified to `attr.s`.
2897
+
2898
+ Returns:
2899
+ type: A new class with *attrs*.
2900
+
2901
+ .. versionadded:: 17.1.0 *bases*
2902
+ .. versionchanged:: 18.1.0 If *attrs* is ordered, the order is retained.
2903
+ .. versionchanged:: 23.2.0 *class_body*
2904
+ """
2905
+ if isinstance(attrs, dict):
2906
+ cls_dict = attrs
2907
+ elif isinstance(attrs, (list, tuple)):
2908
+ cls_dict = {a: attrib() for a in attrs}
2909
+ else:
2910
+ msg = "attrs argument must be a dict or a list."
2911
+ raise TypeError(msg)
2912
+
2913
+ pre_init = cls_dict.pop("__attrs_pre_init__", None)
2914
+ post_init = cls_dict.pop("__attrs_post_init__", None)
2915
+ user_init = cls_dict.pop("__init__", None)
2916
+
2917
+ body = {}
2918
+ if class_body is not None:
2919
+ body.update(class_body)
2920
+ if pre_init is not None:
2921
+ body["__attrs_pre_init__"] = pre_init
2922
+ if post_init is not None:
2923
+ body["__attrs_post_init__"] = post_init
2924
+ if user_init is not None:
2925
+ body["__init__"] = user_init
2926
+
2927
+ type_ = types.new_class(name, bases, {}, lambda ns: ns.update(body))
2928
+
2929
+ # For pickling to work, the __module__ variable needs to be set to the
2930
+ # frame where the class is created. Bypass this step in environments where
2931
+ # sys._getframe is not defined (Jython for example) or sys._getframe is not
2932
+ # defined for arguments greater than 0 (IronPython).
2933
+ with contextlib.suppress(AttributeError, ValueError):
2934
+ type_.__module__ = sys._getframe(1).f_globals.get(
2935
+ "__name__", "__main__"
2936
+ )
2937
+
2938
+ # We do it here for proper warnings with meaningful stacklevel.
2939
+ cmp = attributes_arguments.pop("cmp", None)
2940
+ (
2941
+ attributes_arguments["eq"],
2942
+ attributes_arguments["order"],
2943
+ ) = _determine_attrs_eq_order(
2944
+ cmp,
2945
+ attributes_arguments.get("eq"),
2946
+ attributes_arguments.get("order"),
2947
+ True,
2948
+ )
2949
+
2950
+ cls = _attrs(these=cls_dict, **attributes_arguments)(type_)
2951
+ # Only add type annotations now or "_attrs()" will complain:
2952
+ cls.__annotations__ = {
2953
+ k: v.type for k, v in cls_dict.items() if v.type is not None
2954
+ }
2955
+ return cls
2956
+
2957
+
2958
+ # These are required by within this module so we define them here and merely
2959
+ # import into .validators / .converters.
2960
+
2961
+
2962
+ @attrs(slots=True, unsafe_hash=True)
2963
+ class _AndValidator:
2964
+ """
2965
+ Compose many validators to a single one.
2966
+ """
2967
+
2968
+ _validators = attrib()
2969
+
2970
+ def __call__(self, inst, attr, value):
2971
+ for v in self._validators:
2972
+ v(inst, attr, value)
2973
+
2974
+
2975
+ def and_(*validators):
2976
+ """
2977
+ A validator that composes multiple validators into one.
2978
+
2979
+ When called on a value, it runs all wrapped validators.
2980
+
2981
+ Args:
2982
+ validators (~collections.abc.Iterable[typing.Callable]):
2983
+ Arbitrary number of validators.
2984
+
2985
+ .. versionadded:: 17.1.0
2986
+ """
2987
+ vals = []
2988
+ for validator in validators:
2989
+ vals.extend(
2990
+ validator._validators
2991
+ if isinstance(validator, _AndValidator)
2992
+ else [validator]
2993
+ )
2994
+
2995
+ return _AndValidator(tuple(vals))
2996
+
2997
+
2998
+ def pipe(*converters):
2999
+ """
3000
+ A converter that composes multiple converters into one.
3001
+
3002
+ When called on a value, it runs all wrapped converters, returning the
3003
+ *last* value.
3004
+
3005
+ Type annotations will be inferred from the wrapped converters', if they
3006
+ have any.
3007
+
3008
+ converters (~collections.abc.Iterable[typing.Callable]):
3009
+ Arbitrary number of converters.
3010
+
3011
+ .. versionadded:: 20.1.0
3012
+ """
3013
+
3014
+ return_instance = any(isinstance(c, Converter) for c in converters)
3015
+
3016
+ if return_instance:
3017
+
3018
+ def pipe_converter(val, inst, field):
3019
+ for c in converters:
3020
+ val = (
3021
+ c(val, inst, field) if isinstance(c, Converter) else c(val)
3022
+ )
3023
+
3024
+ return val
3025
+
3026
+ else:
3027
+
3028
+ def pipe_converter(val):
3029
+ for c in converters:
3030
+ val = c(val)
3031
+
3032
+ return val
3033
+
3034
+ if not converters:
3035
+ # If the converter list is empty, pipe_converter is the identity.
3036
+ A = typing.TypeVar("A")
3037
+ pipe_converter.__annotations__.update({"val": A, "return": A})
3038
+ else:
3039
+ # Get parameter type from first converter.
3040
+ t = _AnnotationExtractor(converters[0]).get_first_param_type()
3041
+ if t:
3042
+ pipe_converter.__annotations__["val"] = t
3043
+
3044
+ last = converters[-1]
3045
+ if not PY_3_11_PLUS and isinstance(last, Converter):
3046
+ last = last.__call__
3047
+
3048
+ # Get return type from last converter.
3049
+ rt = _AnnotationExtractor(last).get_return_type()
3050
+ if rt:
3051
+ pipe_converter.__annotations__["return"] = rt
3052
+
3053
+ if return_instance:
3054
+ return Converter(pipe_converter, takes_self=True, takes_field=True)
3055
+ return pipe_converter
vllm/lib/python3.10/site-packages/attr/_next_gen.py ADDED
@@ -0,0 +1,623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ """
4
+ These are keyword-only APIs that call `attr.s` and `attr.ib` with different
5
+ default values.
6
+ """
7
+
8
+ from functools import partial
9
+
10
+ from . import setters
11
+ from ._funcs import asdict as _asdict
12
+ from ._funcs import astuple as _astuple
13
+ from ._make import (
14
+ _DEFAULT_ON_SETATTR,
15
+ NOTHING,
16
+ _frozen_setattrs,
17
+ attrib,
18
+ attrs,
19
+ )
20
+ from .exceptions import UnannotatedAttributeError
21
+
22
+
23
+ def define(
24
+ maybe_cls=None,
25
+ *,
26
+ these=None,
27
+ repr=None,
28
+ unsafe_hash=None,
29
+ hash=None,
30
+ init=None,
31
+ slots=True,
32
+ frozen=False,
33
+ weakref_slot=True,
34
+ str=False,
35
+ auto_attribs=None,
36
+ kw_only=False,
37
+ cache_hash=False,
38
+ auto_exc=True,
39
+ eq=None,
40
+ order=False,
41
+ auto_detect=True,
42
+ getstate_setstate=None,
43
+ on_setattr=None,
44
+ field_transformer=None,
45
+ match_args=True,
46
+ ):
47
+ r"""
48
+ A class decorator that adds :term:`dunder methods` according to
49
+ :term:`fields <field>` specified using :doc:`type annotations <types>`,
50
+ `field()` calls, or the *these* argument.
51
+
52
+ Since *attrs* patches or replaces an existing class, you cannot use
53
+ `object.__init_subclass__` with *attrs* classes, because it runs too early.
54
+ As a replacement, you can define ``__attrs_init_subclass__`` on your class.
55
+ It will be called by *attrs* classes that subclass it after they're
56
+ created. See also :ref:`init-subclass`.
57
+
58
+ Args:
59
+ slots (bool):
60
+ Create a :term:`slotted class <slotted classes>` that's more
61
+ memory-efficient. Slotted classes are generally superior to the
62
+ default dict classes, but have some gotchas you should know about,
63
+ so we encourage you to read the :term:`glossary entry <slotted
64
+ classes>`.
65
+
66
+ auto_detect (bool):
67
+ Instead of setting the *init*, *repr*, *eq*, and *hash* arguments
68
+ explicitly, assume they are set to True **unless any** of the
69
+ involved methods for one of the arguments is implemented in the
70
+ *current* class (meaning, it is *not* inherited from some base
71
+ class).
72
+
73
+ So, for example by implementing ``__eq__`` on a class yourself,
74
+ *attrs* will deduce ``eq=False`` and will create *neither*
75
+ ``__eq__`` *nor* ``__ne__`` (but Python classes come with a
76
+ sensible ``__ne__`` by default, so it *should* be enough to only
77
+ implement ``__eq__`` in most cases).
78
+
79
+ Passing True or False` to *init*, *repr*, *eq*, or *hash*
80
+ overrides whatever *auto_detect* would determine.
81
+
82
+ auto_exc (bool):
83
+ If the class subclasses `BaseException` (which implicitly includes
84
+ any subclass of any exception), the following happens to behave
85
+ like a well-behaved Python exception class:
86
+
87
+ - the values for *eq*, *order*, and *hash* are ignored and the
88
+ instances compare and hash by the instance's ids [#]_ ,
89
+ - all attributes that are either passed into ``__init__`` or have a
90
+ default value are additionally available as a tuple in the
91
+ ``args`` attribute,
92
+ - the value of *str* is ignored leaving ``__str__`` to base
93
+ classes.
94
+
95
+ .. [#]
96
+ Note that *attrs* will *not* remove existing implementations of
97
+ ``__hash__`` or the equality methods. It just won't add own
98
+ ones.
99
+
100
+ on_setattr (~typing.Callable | list[~typing.Callable] | None | ~typing.Literal[attrs.setters.NO_OP]):
101
+ A callable that is run whenever the user attempts to set an
102
+ attribute (either by assignment like ``i.x = 42`` or by using
103
+ `setattr` like ``setattr(i, "x", 42)``). It receives the same
104
+ arguments as validators: the instance, the attribute that is being
105
+ modified, and the new value.
106
+
107
+ If no exception is raised, the attribute is set to the return value
108
+ of the callable.
109
+
110
+ If a list of callables is passed, they're automatically wrapped in
111
+ an `attrs.setters.pipe`.
112
+
113
+ If left None, the default behavior is to run converters and
114
+ validators whenever an attribute is set.
115
+
116
+ init (bool):
117
+ Create a ``__init__`` method that initializes the *attrs*
118
+ attributes. Leading underscores are stripped for the argument name,
119
+ unless an alias is set on the attribute.
120
+
121
+ .. seealso::
122
+ `init` shows advanced ways to customize the generated
123
+ ``__init__`` method, including executing code before and after.
124
+
125
+ repr(bool):
126
+ Create a ``__repr__`` method with a human readable representation
127
+ of *attrs* attributes.
128
+
129
+ str (bool):
130
+ Create a ``__str__`` method that is identical to ``__repr__``. This
131
+ is usually not necessary except for `Exception`\ s.
132
+
133
+ eq (bool | None):
134
+ If True or None (default), add ``__eq__`` and ``__ne__`` methods
135
+ that check two instances for equality.
136
+
137
+ .. seealso::
138
+ `comparison` describes how to customize the comparison behavior
139
+ going as far comparing NumPy arrays.
140
+
141
+ order (bool | None):
142
+ If True, add ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__``
143
+ methods that behave like *eq* above and allow instances to be
144
+ ordered.
145
+
146
+ They compare the instances as if they were tuples of their *attrs*
147
+ attributes if and only if the types of both classes are
148
+ *identical*.
149
+
150
+ If `None` mirror value of *eq*.
151
+
152
+ .. seealso:: `comparison`
153
+
154
+ unsafe_hash (bool | None):
155
+ If None (default), the ``__hash__`` method is generated according
156
+ how *eq* and *frozen* are set.
157
+
158
+ 1. If *both* are True, *attrs* will generate a ``__hash__`` for
159
+ you.
160
+ 2. If *eq* is True and *frozen* is False, ``__hash__`` will be set
161
+ to None, marking it unhashable (which it is).
162
+ 3. If *eq* is False, ``__hash__`` will be left untouched meaning
163
+ the ``__hash__`` method of the base class will be used. If the
164
+ base class is `object`, this means it will fall back to id-based
165
+ hashing.
166
+
167
+ Although not recommended, you can decide for yourself and force
168
+ *attrs* to create one (for example, if the class is immutable even
169
+ though you didn't freeze it programmatically) by passing True or
170
+ not. Both of these cases are rather special and should be used
171
+ carefully.
172
+
173
+ .. seealso::
174
+
175
+ - Our documentation on `hashing`,
176
+ - Python's documentation on `object.__hash__`,
177
+ - and the `GitHub issue that led to the default \ behavior
178
+ <https://github.com/python-attrs/attrs/issues/136>`_ for more
179
+ details.
180
+
181
+ hash (bool | None):
182
+ Deprecated alias for *unsafe_hash*. *unsafe_hash* takes precedence.
183
+
184
+ cache_hash (bool):
185
+ Ensure that the object's hash code is computed only once and stored
186
+ on the object. If this is set to True, hashing must be either
187
+ explicitly or implicitly enabled for this class. If the hash code
188
+ is cached, avoid any reassignments of fields involved in hash code
189
+ computation or mutations of the objects those fields point to after
190
+ object creation. If such changes occur, the behavior of the
191
+ object's hash code is undefined.
192
+
193
+ frozen (bool):
194
+ Make instances immutable after initialization. If someone attempts
195
+ to modify a frozen instance, `attrs.exceptions.FrozenInstanceError`
196
+ is raised.
197
+
198
+ .. note::
199
+
200
+ 1. This is achieved by installing a custom ``__setattr__``
201
+ method on your class, so you can't implement your own.
202
+
203
+ 2. True immutability is impossible in Python.
204
+
205
+ 3. This *does* have a minor a runtime performance `impact
206
+ <how-frozen>` when initializing new instances. In other
207
+ words: ``__init__`` is slightly slower with ``frozen=True``.
208
+
209
+ 4. If a class is frozen, you cannot modify ``self`` in
210
+ ``__attrs_post_init__`` or a self-written ``__init__``. You
211
+ can circumvent that limitation by using
212
+ ``object.__setattr__(self, "attribute_name", value)``.
213
+
214
+ 5. Subclasses of a frozen class are frozen too.
215
+
216
+ kw_only (bool):
217
+ Make all attributes keyword-only in the generated ``__init__`` (if
218
+ *init* is False, this parameter is ignored).
219
+
220
+ weakref_slot (bool):
221
+ Make instances weak-referenceable. This has no effect unless
222
+ *slots* is True.
223
+
224
+ field_transformer (~typing.Callable | None):
225
+ A function that is called with the original class object and all
226
+ fields right before *attrs* finalizes the class. You can use this,
227
+ for example, to automatically add converters or validators to
228
+ fields based on their types.
229
+
230
+ .. seealso:: `transform-fields`
231
+
232
+ match_args (bool):
233
+ If True (default), set ``__match_args__`` on the class to support
234
+ :pep:`634` (*Structural Pattern Matching*). It is a tuple of all
235
+ non-keyword-only ``__init__`` parameter names on Python 3.10 and
236
+ later. Ignored on older Python versions.
237
+
238
+ collect_by_mro (bool):
239
+ If True, *attrs* collects attributes from base classes correctly
240
+ according to the `method resolution order
241
+ <https://docs.python.org/3/howto/mro.html>`_. If False, *attrs*
242
+ will mimic the (wrong) behavior of `dataclasses` and :pep:`681`.
243
+
244
+ See also `issue #428
245
+ <https://github.com/python-attrs/attrs/issues/428>`_.
246
+
247
+ getstate_setstate (bool | None):
248
+ .. note::
249
+
250
+ This is usually only interesting for slotted classes and you
251
+ should probably just set *auto_detect* to True.
252
+
253
+ If True, ``__getstate__`` and ``__setstate__`` are generated and
254
+ attached to the class. This is necessary for slotted classes to be
255
+ pickleable. If left None, it's True by default for slotted classes
256
+ and False for dict classes.
257
+
258
+ If *auto_detect* is True, and *getstate_setstate* is left None, and
259
+ **either** ``__getstate__`` or ``__setstate__`` is detected
260
+ directly on the class (meaning: not inherited), it is set to False
261
+ (this is usually what you want).
262
+
263
+ auto_attribs (bool | None):
264
+ If True, look at type annotations to determine which attributes to
265
+ use, like `dataclasses`. If False, it will only look for explicit
266
+ :func:`field` class attributes, like classic *attrs*.
267
+
268
+ If left None, it will guess:
269
+
270
+ 1. If any attributes are annotated and no unannotated
271
+ `attrs.field`\ s are found, it assumes *auto_attribs=True*.
272
+ 2. Otherwise it assumes *auto_attribs=False* and tries to collect
273
+ `attrs.field`\ s.
274
+
275
+ If *attrs* decides to look at type annotations, **all** fields
276
+ **must** be annotated. If *attrs* encounters a field that is set to
277
+ a :func:`field` / `attr.ib` but lacks a type annotation, an
278
+ `attrs.exceptions.UnannotatedAttributeError` is raised. Use
279
+ ``field_name: typing.Any = field(...)`` if you don't want to set a
280
+ type.
281
+
282
+ .. warning::
283
+
284
+ For features that use the attribute name to create decorators
285
+ (for example, :ref:`validators <validators>`), you still *must*
286
+ assign :func:`field` / `attr.ib` to them. Otherwise Python will
287
+ either not find the name or try to use the default value to
288
+ call, for example, ``validator`` on it.
289
+
290
+ Attributes annotated as `typing.ClassVar`, and attributes that are
291
+ neither annotated nor set to an `field()` are **ignored**.
292
+
293
+ these (dict[str, object]):
294
+ A dictionary of name to the (private) return value of `field()`
295
+ mappings. This is useful to avoid the definition of your attributes
296
+ within the class body because you can't (for example, if you want
297
+ to add ``__repr__`` methods to Django models) or don't want to.
298
+
299
+ If *these* is not `None`, *attrs* will *not* search the class body
300
+ for attributes and will *not* remove any attributes from it.
301
+
302
+ The order is deduced from the order of the attributes inside
303
+ *these*.
304
+
305
+ Arguably, this is a rather obscure feature.
306
+
307
+ .. versionadded:: 20.1.0
308
+ .. versionchanged:: 21.3.0 Converters are also run ``on_setattr``.
309
+ .. versionadded:: 22.2.0
310
+ *unsafe_hash* as an alias for *hash* (for :pep:`681` compliance).
311
+ .. versionchanged:: 24.1.0
312
+ Instances are not compared as tuples of attributes anymore, but using a
313
+ big ``and`` condition. This is faster and has more correct behavior for
314
+ uncomparable values like `math.nan`.
315
+ .. versionadded:: 24.1.0
316
+ If a class has an *inherited* classmethod called
317
+ ``__attrs_init_subclass__``, it is executed after the class is created.
318
+ .. deprecated:: 24.1.0 *hash* is deprecated in favor of *unsafe_hash*.
319
+ .. versionadded:: 24.3.0
320
+ Unless already present, a ``__replace__`` method is automatically
321
+ created for `copy.replace` (Python 3.13+ only).
322
+
323
+ .. note::
324
+
325
+ The main differences to the classic `attr.s` are:
326
+
327
+ - Automatically detect whether or not *auto_attribs* should be `True`
328
+ (c.f. *auto_attribs* parameter).
329
+ - Converters and validators run when attributes are set by default --
330
+ if *frozen* is `False`.
331
+ - *slots=True*
332
+
333
+ Usually, this has only upsides and few visible effects in everyday
334
+ programming. But it *can* lead to some surprising behaviors, so
335
+ please make sure to read :term:`slotted classes`.
336
+
337
+ - *auto_exc=True*
338
+ - *auto_detect=True*
339
+ - *order=False*
340
+ - Some options that were only relevant on Python 2 or were kept around
341
+ for backwards-compatibility have been removed.
342
+
343
+ """
344
+
345
+ def do_it(cls, auto_attribs):
346
+ return attrs(
347
+ maybe_cls=cls,
348
+ these=these,
349
+ repr=repr,
350
+ hash=hash,
351
+ unsafe_hash=unsafe_hash,
352
+ init=init,
353
+ slots=slots,
354
+ frozen=frozen,
355
+ weakref_slot=weakref_slot,
356
+ str=str,
357
+ auto_attribs=auto_attribs,
358
+ kw_only=kw_only,
359
+ cache_hash=cache_hash,
360
+ auto_exc=auto_exc,
361
+ eq=eq,
362
+ order=order,
363
+ auto_detect=auto_detect,
364
+ collect_by_mro=True,
365
+ getstate_setstate=getstate_setstate,
366
+ on_setattr=on_setattr,
367
+ field_transformer=field_transformer,
368
+ match_args=match_args,
369
+ )
370
+
371
+ def wrap(cls):
372
+ """
373
+ Making this a wrapper ensures this code runs during class creation.
374
+
375
+ We also ensure that frozen-ness of classes is inherited.
376
+ """
377
+ nonlocal frozen, on_setattr
378
+
379
+ had_on_setattr = on_setattr not in (None, setters.NO_OP)
380
+
381
+ # By default, mutable classes convert & validate on setattr.
382
+ if frozen is False and on_setattr is None:
383
+ on_setattr = _DEFAULT_ON_SETATTR
384
+
385
+ # However, if we subclass a frozen class, we inherit the immutability
386
+ # and disable on_setattr.
387
+ for base_cls in cls.__bases__:
388
+ if base_cls.__setattr__ is _frozen_setattrs:
389
+ if had_on_setattr:
390
+ msg = "Frozen classes can't use on_setattr (frozen-ness was inherited)."
391
+ raise ValueError(msg)
392
+
393
+ on_setattr = setters.NO_OP
394
+ break
395
+
396
+ if auto_attribs is not None:
397
+ return do_it(cls, auto_attribs)
398
+
399
+ try:
400
+ return do_it(cls, True)
401
+ except UnannotatedAttributeError:
402
+ return do_it(cls, False)
403
+
404
+ # maybe_cls's type depends on the usage of the decorator. It's a class
405
+ # if it's used as `@attrs` but `None` if used as `@attrs()`.
406
+ if maybe_cls is None:
407
+ return wrap
408
+
409
+ return wrap(maybe_cls)
410
+
411
+
412
+ mutable = define
413
+ frozen = partial(define, frozen=True, on_setattr=None)
414
+
415
+
416
+ def field(
417
+ *,
418
+ default=NOTHING,
419
+ validator=None,
420
+ repr=True,
421
+ hash=None,
422
+ init=True,
423
+ metadata=None,
424
+ type=None,
425
+ converter=None,
426
+ factory=None,
427
+ kw_only=False,
428
+ eq=None,
429
+ order=None,
430
+ on_setattr=None,
431
+ alias=None,
432
+ ):
433
+ """
434
+ Create a new :term:`field` / :term:`attribute` on a class.
435
+
436
+ .. warning::
437
+
438
+ Does **nothing** unless the class is also decorated with
439
+ `attrs.define` (or similar)!
440
+
441
+ Args:
442
+ default:
443
+ A value that is used if an *attrs*-generated ``__init__`` is used
444
+ and no value is passed while instantiating or the attribute is
445
+ excluded using ``init=False``.
446
+
447
+ If the value is an instance of `attrs.Factory`, its callable will
448
+ be used to construct a new value (useful for mutable data types
449
+ like lists or dicts).
450
+
451
+ If a default is not set (or set manually to `attrs.NOTHING`), a
452
+ value *must* be supplied when instantiating; otherwise a
453
+ `TypeError` will be raised.
454
+
455
+ .. seealso:: `defaults`
456
+
457
+ factory (~typing.Callable):
458
+ Syntactic sugar for ``default=attr.Factory(factory)``.
459
+
460
+ validator (~typing.Callable | list[~typing.Callable]):
461
+ Callable that is called by *attrs*-generated ``__init__`` methods
462
+ after the instance has been initialized. They receive the
463
+ initialized instance, the :func:`~attrs.Attribute`, and the passed
464
+ value.
465
+
466
+ The return value is *not* inspected so the validator has to throw
467
+ an exception itself.
468
+
469
+ If a `list` is passed, its items are treated as validators and must
470
+ all pass.
471
+
472
+ Validators can be globally disabled and re-enabled using
473
+ `attrs.validators.get_disabled` / `attrs.validators.set_disabled`.
474
+
475
+ The validator can also be set using decorator notation as shown
476
+ below.
477
+
478
+ .. seealso:: :ref:`validators`
479
+
480
+ repr (bool | ~typing.Callable):
481
+ Include this attribute in the generated ``__repr__`` method. If
482
+ True, include the attribute; if False, omit it. By default, the
483
+ built-in ``repr()`` function is used. To override how the attribute
484
+ value is formatted, pass a ``callable`` that takes a single value
485
+ and returns a string. Note that the resulting string is used as-is,
486
+ which means it will be used directly *instead* of calling
487
+ ``repr()`` (the default).
488
+
489
+ eq (bool | ~typing.Callable):
490
+ If True (default), include this attribute in the generated
491
+ ``__eq__`` and ``__ne__`` methods that check two instances for
492
+ equality. To override how the attribute value is compared, pass a
493
+ callable that takes a single value and returns the value to be
494
+ compared.
495
+
496
+ .. seealso:: `comparison`
497
+
498
+ order (bool | ~typing.Callable):
499
+ If True (default), include this attributes in the generated
500
+ ``__lt__``, ``__le__``, ``__gt__`` and ``__ge__`` methods. To
501
+ override how the attribute value is ordered, pass a callable that
502
+ takes a single value and returns the value to be ordered.
503
+
504
+ .. seealso:: `comparison`
505
+
506
+ hash (bool | None):
507
+ Include this attribute in the generated ``__hash__`` method. If
508
+ None (default), mirror *eq*'s value. This is the correct behavior
509
+ according the Python spec. Setting this value to anything else
510
+ than None is *discouraged*.
511
+
512
+ .. seealso:: `hashing`
513
+
514
+ init (bool):
515
+ Include this attribute in the generated ``__init__`` method.
516
+
517
+ It is possible to set this to False and set a default value. In
518
+ that case this attributed is unconditionally initialized with the
519
+ specified default value or factory.
520
+
521
+ .. seealso:: `init`
522
+
523
+ converter (typing.Callable | Converter):
524
+ A callable that is called by *attrs*-generated ``__init__`` methods
525
+ to convert attribute's value to the desired format.
526
+
527
+ If a vanilla callable is passed, it is given the passed-in value as
528
+ the only positional argument. It is possible to receive additional
529
+ arguments by wrapping the callable in a `Converter`.
530
+
531
+ Either way, the returned value will be used as the new value of the
532
+ attribute. The value is converted before being passed to the
533
+ validator, if any.
534
+
535
+ .. seealso:: :ref:`converters`
536
+
537
+ metadata (dict | None):
538
+ An arbitrary mapping, to be used by third-party code.
539
+
540
+ .. seealso:: `extending-metadata`.
541
+
542
+ type (type):
543
+ The type of the attribute. Nowadays, the preferred method to
544
+ specify the type is using a variable annotation (see :pep:`526`).
545
+ This argument is provided for backwards-compatibility and for usage
546
+ with `make_class`. Regardless of the approach used, the type will
547
+ be stored on ``Attribute.type``.
548
+
549
+ Please note that *attrs* doesn't do anything with this metadata by
550
+ itself. You can use it as part of your own code or for `static type
551
+ checking <types>`.
552
+
553
+ kw_only (bool):
554
+ Make this attribute keyword-only in the generated ``__init__`` (if
555
+ ``init`` is False, this parameter is ignored).
556
+
557
+ on_setattr (~typing.Callable | list[~typing.Callable] | None | ~typing.Literal[attrs.setters.NO_OP]):
558
+ Allows to overwrite the *on_setattr* setting from `attr.s`. If left
559
+ None, the *on_setattr* value from `attr.s` is used. Set to
560
+ `attrs.setters.NO_OP` to run **no** `setattr` hooks for this
561
+ attribute -- regardless of the setting in `define()`.
562
+
563
+ alias (str | None):
564
+ Override this attribute's parameter name in the generated
565
+ ``__init__`` method. If left None, default to ``name`` stripped
566
+ of leading underscores. See `private-attributes`.
567
+
568
+ .. versionadded:: 20.1.0
569
+ .. versionchanged:: 21.1.0
570
+ *eq*, *order*, and *cmp* also accept a custom callable
571
+ .. versionadded:: 22.2.0 *alias*
572
+ .. versionadded:: 23.1.0
573
+ The *type* parameter has been re-added; mostly for `attrs.make_class`.
574
+ Please note that type checkers ignore this metadata.
575
+
576
+ .. seealso::
577
+
578
+ `attr.ib`
579
+ """
580
+ return attrib(
581
+ default=default,
582
+ validator=validator,
583
+ repr=repr,
584
+ hash=hash,
585
+ init=init,
586
+ metadata=metadata,
587
+ type=type,
588
+ converter=converter,
589
+ factory=factory,
590
+ kw_only=kw_only,
591
+ eq=eq,
592
+ order=order,
593
+ on_setattr=on_setattr,
594
+ alias=alias,
595
+ )
596
+
597
+
598
+ def asdict(inst, *, recurse=True, filter=None, value_serializer=None):
599
+ """
600
+ Same as `attr.asdict`, except that collections types are always retained
601
+ and dict is always used as *dict_factory*.
602
+
603
+ .. versionadded:: 21.3.0
604
+ """
605
+ return _asdict(
606
+ inst=inst,
607
+ recurse=recurse,
608
+ filter=filter,
609
+ value_serializer=value_serializer,
610
+ retain_collection_types=True,
611
+ )
612
+
613
+
614
+ def astuple(inst, *, recurse=True, filter=None):
615
+ """
616
+ Same as `attr.astuple`, except that collections types are always retained
617
+ and `tuple` is always used as the *tuple_factory*.
618
+
619
+ .. versionadded:: 21.3.0
620
+ """
621
+ return _astuple(
622
+ inst=inst, recurse=recurse, filter=filter, retain_collection_types=True
623
+ )
vllm/lib/python3.10/site-packages/attr/_typing_compat.pyi ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, ClassVar, Protocol
2
+
3
+ # MYPY is a special constant in mypy which works the same way as `TYPE_CHECKING`.
4
+ MYPY = False
5
+
6
+ if MYPY:
7
+ # A protocol to be able to statically accept an attrs class.
8
+ class AttrsInstance_(Protocol):
9
+ __attrs_attrs__: ClassVar[Any]
10
+
11
+ else:
12
+ # For type checkers without plug-in support use an empty protocol that
13
+ # will (hopefully) be combined into a union.
14
+ class AttrsInstance_(Protocol):
15
+ pass
vllm/lib/python3.10/site-packages/attr/_version_info.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+
4
+ from functools import total_ordering
5
+
6
+ from ._funcs import astuple
7
+ from ._make import attrib, attrs
8
+
9
+
10
+ @total_ordering
11
+ @attrs(eq=False, order=False, slots=True, frozen=True)
12
+ class VersionInfo:
13
+ """
14
+ A version object that can be compared to tuple of length 1--4:
15
+
16
+ >>> attr.VersionInfo(19, 1, 0, "final") <= (19, 2)
17
+ True
18
+ >>> attr.VersionInfo(19, 1, 0, "final") < (19, 1, 1)
19
+ True
20
+ >>> vi = attr.VersionInfo(19, 2, 0, "final")
21
+ >>> vi < (19, 1, 1)
22
+ False
23
+ >>> vi < (19,)
24
+ False
25
+ >>> vi == (19, 2,)
26
+ True
27
+ >>> vi == (19, 2, 1)
28
+ False
29
+
30
+ .. versionadded:: 19.2
31
+ """
32
+
33
+ year = attrib(type=int)
34
+ minor = attrib(type=int)
35
+ micro = attrib(type=int)
36
+ releaselevel = attrib(type=str)
37
+
38
+ @classmethod
39
+ def _from_version_string(cls, s):
40
+ """
41
+ Parse *s* and return a _VersionInfo.
42
+ """
43
+ v = s.split(".")
44
+ if len(v) == 3:
45
+ v.append("final")
46
+
47
+ return cls(
48
+ year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]
49
+ )
50
+
51
+ def _ensure_tuple(self, other):
52
+ """
53
+ Ensure *other* is a tuple of a valid length.
54
+
55
+ Returns a possibly transformed *other* and ourselves as a tuple of
56
+ the same length as *other*.
57
+ """
58
+
59
+ if self.__class__ is other.__class__:
60
+ other = astuple(other)
61
+
62
+ if not isinstance(other, tuple):
63
+ raise NotImplementedError
64
+
65
+ if not (1 <= len(other) <= 4):
66
+ raise NotImplementedError
67
+
68
+ return astuple(self)[: len(other)], other
69
+
70
+ def __eq__(self, other):
71
+ try:
72
+ us, them = self._ensure_tuple(other)
73
+ except NotImplementedError:
74
+ return NotImplemented
75
+
76
+ return us == them
77
+
78
+ def __lt__(self, other):
79
+ try:
80
+ us, them = self._ensure_tuple(other)
81
+ except NotImplementedError:
82
+ return NotImplemented
83
+
84
+ # Since alphabetically "dev0" < "final" < "post1" < "post2", we don't
85
+ # have to do anything special with releaselevel for now.
86
+ return us < them
vllm/lib/python3.10/site-packages/attr/_version_info.pyi ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ class VersionInfo:
2
+ @property
3
+ def year(self) -> int: ...
4
+ @property
5
+ def minor(self) -> int: ...
6
+ @property
7
+ def micro(self) -> int: ...
8
+ @property
9
+ def releaselevel(self) -> str: ...
vllm/lib/python3.10/site-packages/attr/converters.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ """
4
+ Commonly useful converters.
5
+ """
6
+
7
+ import typing
8
+
9
+ from ._compat import _AnnotationExtractor
10
+ from ._make import NOTHING, Converter, Factory, pipe
11
+
12
+
13
+ __all__ = [
14
+ "default_if_none",
15
+ "optional",
16
+ "pipe",
17
+ "to_bool",
18
+ ]
19
+
20
+
21
+ def optional(converter):
22
+ """
23
+ A converter that allows an attribute to be optional. An optional attribute
24
+ is one which can be set to `None`.
25
+
26
+ Type annotations will be inferred from the wrapped converter's, if it has
27
+ any.
28
+
29
+ Args:
30
+ converter (typing.Callable):
31
+ the converter that is used for non-`None` values.
32
+
33
+ .. versionadded:: 17.1.0
34
+ """
35
+
36
+ if isinstance(converter, Converter):
37
+
38
+ def optional_converter(val, inst, field):
39
+ if val is None:
40
+ return None
41
+ return converter(val, inst, field)
42
+
43
+ else:
44
+
45
+ def optional_converter(val):
46
+ if val is None:
47
+ return None
48
+ return converter(val)
49
+
50
+ xtr = _AnnotationExtractor(converter)
51
+
52
+ t = xtr.get_first_param_type()
53
+ if t:
54
+ optional_converter.__annotations__["val"] = typing.Optional[t]
55
+
56
+ rt = xtr.get_return_type()
57
+ if rt:
58
+ optional_converter.__annotations__["return"] = typing.Optional[rt]
59
+
60
+ if isinstance(converter, Converter):
61
+ return Converter(optional_converter, takes_self=True, takes_field=True)
62
+
63
+ return optional_converter
64
+
65
+
66
+ def default_if_none(default=NOTHING, factory=None):
67
+ """
68
+ A converter that allows to replace `None` values by *default* or the result
69
+ of *factory*.
70
+
71
+ Args:
72
+ default:
73
+ Value to be used if `None` is passed. Passing an instance of
74
+ `attrs.Factory` is supported, however the ``takes_self`` option is
75
+ *not*.
76
+
77
+ factory (typing.Callable):
78
+ A callable that takes no parameters whose result is used if `None`
79
+ is passed.
80
+
81
+ Raises:
82
+ TypeError: If **neither** *default* or *factory* is passed.
83
+
84
+ TypeError: If **both** *default* and *factory* are passed.
85
+
86
+ ValueError:
87
+ If an instance of `attrs.Factory` is passed with
88
+ ``takes_self=True``.
89
+
90
+ .. versionadded:: 18.2.0
91
+ """
92
+ if default is NOTHING and factory is None:
93
+ msg = "Must pass either `default` or `factory`."
94
+ raise TypeError(msg)
95
+
96
+ if default is not NOTHING and factory is not None:
97
+ msg = "Must pass either `default` or `factory` but not both."
98
+ raise TypeError(msg)
99
+
100
+ if factory is not None:
101
+ default = Factory(factory)
102
+
103
+ if isinstance(default, Factory):
104
+ if default.takes_self:
105
+ msg = "`takes_self` is not supported by default_if_none."
106
+ raise ValueError(msg)
107
+
108
+ def default_if_none_converter(val):
109
+ if val is not None:
110
+ return val
111
+
112
+ return default.factory()
113
+
114
+ else:
115
+
116
+ def default_if_none_converter(val):
117
+ if val is not None:
118
+ return val
119
+
120
+ return default
121
+
122
+ return default_if_none_converter
123
+
124
+
125
+ def to_bool(val):
126
+ """
127
+ Convert "boolean" strings (for example, from environment variables) to real
128
+ booleans.
129
+
130
+ Values mapping to `True`:
131
+
132
+ - ``True``
133
+ - ``"true"`` / ``"t"``
134
+ - ``"yes"`` / ``"y"``
135
+ - ``"on"``
136
+ - ``"1"``
137
+ - ``1``
138
+
139
+ Values mapping to `False`:
140
+
141
+ - ``False``
142
+ - ``"false"`` / ``"f"``
143
+ - ``"no"`` / ``"n"``
144
+ - ``"off"``
145
+ - ``"0"``
146
+ - ``0``
147
+
148
+ Raises:
149
+ ValueError: For any other value.
150
+
151
+ .. versionadded:: 21.3.0
152
+ """
153
+ if isinstance(val, str):
154
+ val = val.lower()
155
+
156
+ if val in (True, "true", "t", "yes", "y", "on", "1", 1):
157
+ return True
158
+ if val in (False, "false", "f", "no", "n", "off", "0", 0):
159
+ return False
160
+
161
+ msg = f"Cannot convert value to bool: {val!r}"
162
+ raise ValueError(msg)
vllm/lib/python3.10/site-packages/attr/converters.pyi ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Any, overload
2
+
3
+ from attrs import _ConverterType, _CallableConverterType
4
+
5
+ @overload
6
+ def pipe(*validators: _CallableConverterType) -> _CallableConverterType: ...
7
+ @overload
8
+ def pipe(*validators: _ConverterType) -> _ConverterType: ...
9
+ @overload
10
+ def optional(converter: _CallableConverterType) -> _CallableConverterType: ...
11
+ @overload
12
+ def optional(converter: _ConverterType) -> _ConverterType: ...
13
+ @overload
14
+ def default_if_none(default: Any) -> _CallableConverterType: ...
15
+ @overload
16
+ def default_if_none(
17
+ *, factory: Callable[[], Any]
18
+ ) -> _CallableConverterType: ...
19
+ def to_bool(val: str | int | bool) -> bool: ...
vllm/lib/python3.10/site-packages/attr/exceptions.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import ClassVar
6
+
7
+
8
+ class FrozenError(AttributeError):
9
+ """
10
+ A frozen/immutable instance or attribute have been attempted to be
11
+ modified.
12
+
13
+ It mirrors the behavior of ``namedtuples`` by using the same error message
14
+ and subclassing `AttributeError`.
15
+
16
+ .. versionadded:: 20.1.0
17
+ """
18
+
19
+ msg = "can't set attribute"
20
+ args: ClassVar[tuple[str]] = [msg]
21
+
22
+
23
+ class FrozenInstanceError(FrozenError):
24
+ """
25
+ A frozen instance has been attempted to be modified.
26
+
27
+ .. versionadded:: 16.1.0
28
+ """
29
+
30
+
31
+ class FrozenAttributeError(FrozenError):
32
+ """
33
+ A frozen attribute has been attempted to be modified.
34
+
35
+ .. versionadded:: 20.1.0
36
+ """
37
+
38
+
39
+ class AttrsAttributeNotFoundError(ValueError):
40
+ """
41
+ An *attrs* function couldn't find an attribute that the user asked for.
42
+
43
+ .. versionadded:: 16.2.0
44
+ """
45
+
46
+
47
+ class NotAnAttrsClassError(ValueError):
48
+ """
49
+ A non-*attrs* class has been passed into an *attrs* function.
50
+
51
+ .. versionadded:: 16.2.0
52
+ """
53
+
54
+
55
+ class DefaultAlreadySetError(RuntimeError):
56
+ """
57
+ A default has been set when defining the field and is attempted to be reset
58
+ using the decorator.
59
+
60
+ .. versionadded:: 17.1.0
61
+ """
62
+
63
+
64
+ class UnannotatedAttributeError(RuntimeError):
65
+ """
66
+ A class with ``auto_attribs=True`` has a field without a type annotation.
67
+
68
+ .. versionadded:: 17.3.0
69
+ """
70
+
71
+
72
+ class PythonTooOldError(RuntimeError):
73
+ """
74
+ It was attempted to use an *attrs* feature that requires a newer Python
75
+ version.
76
+
77
+ .. versionadded:: 18.2.0
78
+ """
79
+
80
+
81
+ class NotCallableError(TypeError):
82
+ """
83
+ A field requiring a callable has been set with a value that is not
84
+ callable.
85
+
86
+ .. versionadded:: 19.2.0
87
+ """
88
+
89
+ def __init__(self, msg, value):
90
+ super(TypeError, self).__init__(msg, value)
91
+ self.msg = msg
92
+ self.value = value
93
+
94
+ def __str__(self):
95
+ return str(self.msg)
vllm/lib/python3.10/site-packages/attr/exceptions.pyi ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ class FrozenError(AttributeError):
4
+ msg: str = ...
5
+
6
+ class FrozenInstanceError(FrozenError): ...
7
+ class FrozenAttributeError(FrozenError): ...
8
+ class AttrsAttributeNotFoundError(ValueError): ...
9
+ class NotAnAttrsClassError(ValueError): ...
10
+ class DefaultAlreadySetError(RuntimeError): ...
11
+ class UnannotatedAttributeError(RuntimeError): ...
12
+ class PythonTooOldError(RuntimeError): ...
13
+
14
+ class NotCallableError(TypeError):
15
+ msg: str = ...
16
+ value: Any = ...
17
+ def __init__(self, msg: str, value: Any) -> None: ...
vllm/lib/python3.10/site-packages/attr/filters.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ """
4
+ Commonly useful filters for `attrs.asdict` and `attrs.astuple`.
5
+ """
6
+
7
+ from ._make import Attribute
8
+
9
+
10
+ def _split_what(what):
11
+ """
12
+ Returns a tuple of `frozenset`s of classes and attributes.
13
+ """
14
+ return (
15
+ frozenset(cls for cls in what if isinstance(cls, type)),
16
+ frozenset(cls for cls in what if isinstance(cls, str)),
17
+ frozenset(cls for cls in what if isinstance(cls, Attribute)),
18
+ )
19
+
20
+
21
+ def include(*what):
22
+ """
23
+ Create a filter that only allows *what*.
24
+
25
+ Args:
26
+ what (list[type, str, attrs.Attribute]):
27
+ What to include. Can be a type, a name, or an attribute.
28
+
29
+ Returns:
30
+ Callable:
31
+ A callable that can be passed to `attrs.asdict`'s and
32
+ `attrs.astuple`'s *filter* argument.
33
+
34
+ .. versionchanged:: 23.1.0 Accept strings with field names.
35
+ """
36
+ cls, names, attrs = _split_what(what)
37
+
38
+ def include_(attribute, value):
39
+ return (
40
+ value.__class__ in cls
41
+ or attribute.name in names
42
+ or attribute in attrs
43
+ )
44
+
45
+ return include_
46
+
47
+
48
+ def exclude(*what):
49
+ """
50
+ Create a filter that does **not** allow *what*.
51
+
52
+ Args:
53
+ what (list[type, str, attrs.Attribute]):
54
+ What to exclude. Can be a type, a name, or an attribute.
55
+
56
+ Returns:
57
+ Callable:
58
+ A callable that can be passed to `attrs.asdict`'s and
59
+ `attrs.astuple`'s *filter* argument.
60
+
61
+ .. versionchanged:: 23.3.0 Accept field name string as input argument
62
+ """
63
+ cls, names, attrs = _split_what(what)
64
+
65
+ def exclude_(attribute, value):
66
+ return not (
67
+ value.__class__ in cls
68
+ or attribute.name in names
69
+ or attribute in attrs
70
+ )
71
+
72
+ return exclude_
vllm/lib/python3.10/site-packages/attr/filters.pyi ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from . import Attribute, _FilterType
4
+
5
+ def include(*what: type | str | Attribute[Any]) -> _FilterType[Any]: ...
6
+ def exclude(*what: type | str | Attribute[Any]) -> _FilterType[Any]: ...
vllm/lib/python3.10/site-packages/attr/py.typed ADDED
File without changes
vllm/lib/python3.10/site-packages/attr/setters.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ """
4
+ Commonly used hooks for on_setattr.
5
+ """
6
+
7
+ from . import _config
8
+ from .exceptions import FrozenAttributeError
9
+
10
+
11
+ def pipe(*setters):
12
+ """
13
+ Run all *setters* and return the return value of the last one.
14
+
15
+ .. versionadded:: 20.1.0
16
+ """
17
+
18
+ def wrapped_pipe(instance, attrib, new_value):
19
+ rv = new_value
20
+
21
+ for setter in setters:
22
+ rv = setter(instance, attrib, rv)
23
+
24
+ return rv
25
+
26
+ return wrapped_pipe
27
+
28
+
29
+ def frozen(_, __, ___):
30
+ """
31
+ Prevent an attribute to be modified.
32
+
33
+ .. versionadded:: 20.1.0
34
+ """
35
+ raise FrozenAttributeError
36
+
37
+
38
+ def validate(instance, attrib, new_value):
39
+ """
40
+ Run *attrib*'s validator on *new_value* if it has one.
41
+
42
+ .. versionadded:: 20.1.0
43
+ """
44
+ if _config._run_validators is False:
45
+ return new_value
46
+
47
+ v = attrib.validator
48
+ if not v:
49
+ return new_value
50
+
51
+ v(instance, attrib, new_value)
52
+
53
+ return new_value
54
+
55
+
56
+ def convert(instance, attrib, new_value):
57
+ """
58
+ Run *attrib*'s converter -- if it has one -- on *new_value* and return the
59
+ result.
60
+
61
+ .. versionadded:: 20.1.0
62
+ """
63
+ c = attrib.converter
64
+ if c:
65
+ # This can be removed once we drop 3.8 and use attrs.Converter instead.
66
+ from ._make import Converter
67
+
68
+ if not isinstance(c, Converter):
69
+ return c(new_value)
70
+
71
+ return c(new_value, instance, attrib)
72
+
73
+ return new_value
74
+
75
+
76
+ # Sentinel for disabling class-wide *on_setattr* hooks for certain attributes.
77
+ # Sphinx's autodata stopped working, so the docstring is inlined in the API
78
+ # docs.
79
+ NO_OP = object()
vllm/lib/python3.10/site-packages/attr/setters.pyi ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, NewType, NoReturn, TypeVar
2
+
3
+ from . import Attribute
4
+ from attrs import _OnSetAttrType
5
+
6
+ _T = TypeVar("_T")
7
+
8
+ def frozen(
9
+ instance: Any, attribute: Attribute[Any], new_value: Any
10
+ ) -> NoReturn: ...
11
+ def pipe(*setters: _OnSetAttrType) -> _OnSetAttrType: ...
12
+ def validate(instance: Any, attribute: Attribute[_T], new_value: _T) -> _T: ...
13
+
14
+ # convert is allowed to return Any, because they can be chained using pipe.
15
+ def convert(
16
+ instance: Any, attribute: Attribute[Any], new_value: Any
17
+ ) -> Any: ...
18
+
19
+ _NoOpType = NewType("_NoOpType", object)
20
+ NO_OP: _NoOpType
vllm/lib/python3.10/site-packages/attr/validators.py ADDED
@@ -0,0 +1,710 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ """
4
+ Commonly useful validators.
5
+ """
6
+
7
+ import operator
8
+ import re
9
+
10
+ from contextlib import contextmanager
11
+ from re import Pattern
12
+
13
+ from ._config import get_run_validators, set_run_validators
14
+ from ._make import _AndValidator, and_, attrib, attrs
15
+ from .converters import default_if_none
16
+ from .exceptions import NotCallableError
17
+
18
+
19
+ __all__ = [
20
+ "and_",
21
+ "deep_iterable",
22
+ "deep_mapping",
23
+ "disabled",
24
+ "ge",
25
+ "get_disabled",
26
+ "gt",
27
+ "in_",
28
+ "instance_of",
29
+ "is_callable",
30
+ "le",
31
+ "lt",
32
+ "matches_re",
33
+ "max_len",
34
+ "min_len",
35
+ "not_",
36
+ "optional",
37
+ "or_",
38
+ "set_disabled",
39
+ ]
40
+
41
+
42
+ def set_disabled(disabled):
43
+ """
44
+ Globally disable or enable running validators.
45
+
46
+ By default, they are run.
47
+
48
+ Args:
49
+ disabled (bool): If `True`, disable running all validators.
50
+
51
+ .. warning::
52
+
53
+ This function is not thread-safe!
54
+
55
+ .. versionadded:: 21.3.0
56
+ """
57
+ set_run_validators(not disabled)
58
+
59
+
60
+ def get_disabled():
61
+ """
62
+ Return a bool indicating whether validators are currently disabled or not.
63
+
64
+ Returns:
65
+ bool:`True` if validators are currently disabled.
66
+
67
+ .. versionadded:: 21.3.0
68
+ """
69
+ return not get_run_validators()
70
+
71
+
72
+ @contextmanager
73
+ def disabled():
74
+ """
75
+ Context manager that disables running validators within its context.
76
+
77
+ .. warning::
78
+
79
+ This context manager is not thread-safe!
80
+
81
+ .. versionadded:: 21.3.0
82
+ """
83
+ set_run_validators(False)
84
+ try:
85
+ yield
86
+ finally:
87
+ set_run_validators(True)
88
+
89
+
90
+ @attrs(repr=False, slots=True, unsafe_hash=True)
91
+ class _InstanceOfValidator:
92
+ type = attrib()
93
+
94
+ def __call__(self, inst, attr, value):
95
+ """
96
+ We use a callable class to be able to change the ``__repr__``.
97
+ """
98
+ if not isinstance(value, self.type):
99
+ msg = f"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r})."
100
+ raise TypeError(
101
+ msg,
102
+ attr,
103
+ self.type,
104
+ value,
105
+ )
106
+
107
+ def __repr__(self):
108
+ return f"<instance_of validator for type {self.type!r}>"
109
+
110
+
111
+ def instance_of(type):
112
+ """
113
+ A validator that raises a `TypeError` if the initializer is called with a
114
+ wrong type for this particular attribute (checks are performed using
115
+ `isinstance` therefore it's also valid to pass a tuple of types).
116
+
117
+ Args:
118
+ type (type | tuple[type]): The type to check for.
119
+
120
+ Raises:
121
+ TypeError:
122
+ With a human readable error message, the attribute (of type
123
+ `attrs.Attribute`), the expected type, and the value it got.
124
+ """
125
+ return _InstanceOfValidator(type)
126
+
127
+
128
+ @attrs(repr=False, frozen=True, slots=True)
129
+ class _MatchesReValidator:
130
+ pattern = attrib()
131
+ match_func = attrib()
132
+
133
+ def __call__(self, inst, attr, value):
134
+ """
135
+ We use a callable class to be able to change the ``__repr__``.
136
+ """
137
+ if not self.match_func(value):
138
+ msg = f"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)"
139
+ raise ValueError(
140
+ msg,
141
+ attr,
142
+ self.pattern,
143
+ value,
144
+ )
145
+
146
+ def __repr__(self):
147
+ return f"<matches_re validator for pattern {self.pattern!r}>"
148
+
149
+
150
+ def matches_re(regex, flags=0, func=None):
151
+ r"""
152
+ A validator that raises `ValueError` if the initializer is called with a
153
+ string that doesn't match *regex*.
154
+
155
+ Args:
156
+ regex (str, re.Pattern):
157
+ A regex string or precompiled pattern to match against
158
+
159
+ flags (int):
160
+ Flags that will be passed to the underlying re function (default 0)
161
+
162
+ func (typing.Callable):
163
+ Which underlying `re` function to call. Valid options are
164
+ `re.fullmatch`, `re.search`, and `re.match`; the default `None`
165
+ means `re.fullmatch`. For performance reasons, the pattern is
166
+ always precompiled using `re.compile`.
167
+
168
+ .. versionadded:: 19.2.0
169
+ .. versionchanged:: 21.3.0 *regex* can be a pre-compiled pattern.
170
+ """
171
+ valid_funcs = (re.fullmatch, None, re.search, re.match)
172
+ if func not in valid_funcs:
173
+ msg = "'func' must be one of {}.".format(
174
+ ", ".join(
175
+ sorted((e and e.__name__) or "None" for e in set(valid_funcs))
176
+ )
177
+ )
178
+ raise ValueError(msg)
179
+
180
+ if isinstance(regex, Pattern):
181
+ if flags:
182
+ msg = "'flags' can only be used with a string pattern; pass flags to re.compile() instead"
183
+ raise TypeError(msg)
184
+ pattern = regex
185
+ else:
186
+ pattern = re.compile(regex, flags)
187
+
188
+ if func is re.match:
189
+ match_func = pattern.match
190
+ elif func is re.search:
191
+ match_func = pattern.search
192
+ else:
193
+ match_func = pattern.fullmatch
194
+
195
+ return _MatchesReValidator(pattern, match_func)
196
+
197
+
198
+ @attrs(repr=False, slots=True, unsafe_hash=True)
199
+ class _OptionalValidator:
200
+ validator = attrib()
201
+
202
+ def __call__(self, inst, attr, value):
203
+ if value is None:
204
+ return
205
+
206
+ self.validator(inst, attr, value)
207
+
208
+ def __repr__(self):
209
+ return f"<optional validator for {self.validator!r} or None>"
210
+
211
+
212
+ def optional(validator):
213
+ """
214
+ A validator that makes an attribute optional. An optional attribute is one
215
+ which can be set to `None` in addition to satisfying the requirements of
216
+ the sub-validator.
217
+
218
+ Args:
219
+ validator
220
+ (typing.Callable | tuple[typing.Callable] | list[typing.Callable]):
221
+ A validator (or validators) that is used for non-`None` values.
222
+
223
+ .. versionadded:: 15.1.0
224
+ .. versionchanged:: 17.1.0 *validator* can be a list of validators.
225
+ .. versionchanged:: 23.1.0 *validator* can also be a tuple of validators.
226
+ """
227
+ if isinstance(validator, (list, tuple)):
228
+ return _OptionalValidator(_AndValidator(validator))
229
+
230
+ return _OptionalValidator(validator)
231
+
232
+
233
+ @attrs(repr=False, slots=True, unsafe_hash=True)
234
+ class _InValidator:
235
+ options = attrib()
236
+ _original_options = attrib(hash=False)
237
+
238
+ def __call__(self, inst, attr, value):
239
+ try:
240
+ in_options = value in self.options
241
+ except TypeError: # e.g. `1 in "abc"`
242
+ in_options = False
243
+
244
+ if not in_options:
245
+ msg = f"'{attr.name}' must be in {self._original_options!r} (got {value!r})"
246
+ raise ValueError(
247
+ msg,
248
+ attr,
249
+ self._original_options,
250
+ value,
251
+ )
252
+
253
+ def __repr__(self):
254
+ return f"<in_ validator with options {self._original_options!r}>"
255
+
256
+
257
+ def in_(options):
258
+ """
259
+ A validator that raises a `ValueError` if the initializer is called with a
260
+ value that does not belong in the *options* provided.
261
+
262
+ The check is performed using ``value in options``, so *options* has to
263
+ support that operation.
264
+
265
+ To keep the validator hashable, dicts, lists, and sets are transparently
266
+ transformed into a `tuple`.
267
+
268
+ Args:
269
+ options: Allowed options.
270
+
271
+ Raises:
272
+ ValueError:
273
+ With a human readable error message, the attribute (of type
274
+ `attrs.Attribute`), the expected options, and the value it got.
275
+
276
+ .. versionadded:: 17.1.0
277
+ .. versionchanged:: 22.1.0
278
+ The ValueError was incomplete until now and only contained the human
279
+ readable error message. Now it contains all the information that has
280
+ been promised since 17.1.0.
281
+ .. versionchanged:: 24.1.0
282
+ *options* that are a list, dict, or a set are now transformed into a
283
+ tuple to keep the validator hashable.
284
+ """
285
+ repr_options = options
286
+ if isinstance(options, (list, dict, set)):
287
+ options = tuple(options)
288
+
289
+ return _InValidator(options, repr_options)
290
+
291
+
292
+ @attrs(repr=False, slots=False, unsafe_hash=True)
293
+ class _IsCallableValidator:
294
+ def __call__(self, inst, attr, value):
295
+ """
296
+ We use a callable class to be able to change the ``__repr__``.
297
+ """
298
+ if not callable(value):
299
+ message = (
300
+ "'{name}' must be callable "
301
+ "(got {value!r} that is a {actual!r})."
302
+ )
303
+ raise NotCallableError(
304
+ msg=message.format(
305
+ name=attr.name, value=value, actual=value.__class__
306
+ ),
307
+ value=value,
308
+ )
309
+
310
+ def __repr__(self):
311
+ return "<is_callable validator>"
312
+
313
+
314
+ def is_callable():
315
+ """
316
+ A validator that raises a `attrs.exceptions.NotCallableError` if the
317
+ initializer is called with a value for this particular attribute that is
318
+ not callable.
319
+
320
+ .. versionadded:: 19.1.0
321
+
322
+ Raises:
323
+ attrs.exceptions.NotCallableError:
324
+ With a human readable error message containing the attribute
325
+ (`attrs.Attribute`) name, and the value it got.
326
+ """
327
+ return _IsCallableValidator()
328
+
329
+
330
+ @attrs(repr=False, slots=True, unsafe_hash=True)
331
+ class _DeepIterable:
332
+ member_validator = attrib(validator=is_callable())
333
+ iterable_validator = attrib(
334
+ default=None, validator=optional(is_callable())
335
+ )
336
+
337
+ def __call__(self, inst, attr, value):
338
+ """
339
+ We use a callable class to be able to change the ``__repr__``.
340
+ """
341
+ if self.iterable_validator is not None:
342
+ self.iterable_validator(inst, attr, value)
343
+
344
+ for member in value:
345
+ self.member_validator(inst, attr, member)
346
+
347
+ def __repr__(self):
348
+ iterable_identifier = (
349
+ ""
350
+ if self.iterable_validator is None
351
+ else f" {self.iterable_validator!r}"
352
+ )
353
+ return (
354
+ f"<deep_iterable validator for{iterable_identifier}"
355
+ f" iterables of {self.member_validator!r}>"
356
+ )
357
+
358
+
359
+ def deep_iterable(member_validator, iterable_validator=None):
360
+ """
361
+ A validator that performs deep validation of an iterable.
362
+
363
+ Args:
364
+ member_validator: Validator to apply to iterable members.
365
+
366
+ iterable_validator:
367
+ Validator to apply to iterable itself (optional).
368
+
369
+ Raises
370
+ TypeError: if any sub-validators fail
371
+
372
+ .. versionadded:: 19.1.0
373
+ """
374
+ if isinstance(member_validator, (list, tuple)):
375
+ member_validator = and_(*member_validator)
376
+ return _DeepIterable(member_validator, iterable_validator)
377
+
378
+
379
+ @attrs(repr=False, slots=True, unsafe_hash=True)
380
+ class _DeepMapping:
381
+ key_validator = attrib(validator=is_callable())
382
+ value_validator = attrib(validator=is_callable())
383
+ mapping_validator = attrib(default=None, validator=optional(is_callable()))
384
+
385
+ def __call__(self, inst, attr, value):
386
+ """
387
+ We use a callable class to be able to change the ``__repr__``.
388
+ """
389
+ if self.mapping_validator is not None:
390
+ self.mapping_validator(inst, attr, value)
391
+
392
+ for key in value:
393
+ self.key_validator(inst, attr, key)
394
+ self.value_validator(inst, attr, value[key])
395
+
396
+ def __repr__(self):
397
+ return f"<deep_mapping validator for objects mapping {self.key_validator!r} to {self.value_validator!r}>"
398
+
399
+
400
+ def deep_mapping(key_validator, value_validator, mapping_validator=None):
401
+ """
402
+ A validator that performs deep validation of a dictionary.
403
+
404
+ Args:
405
+ key_validator: Validator to apply to dictionary keys.
406
+
407
+ value_validator: Validator to apply to dictionary values.
408
+
409
+ mapping_validator:
410
+ Validator to apply to top-level mapping attribute (optional).
411
+
412
+ .. versionadded:: 19.1.0
413
+
414
+ Raises:
415
+ TypeError: if any sub-validators fail
416
+ """
417
+ return _DeepMapping(key_validator, value_validator, mapping_validator)
418
+
419
+
420
+ @attrs(repr=False, frozen=True, slots=True)
421
+ class _NumberValidator:
422
+ bound = attrib()
423
+ compare_op = attrib()
424
+ compare_func = attrib()
425
+
426
+ def __call__(self, inst, attr, value):
427
+ """
428
+ We use a callable class to be able to change the ``__repr__``.
429
+ """
430
+ if not self.compare_func(value, self.bound):
431
+ msg = f"'{attr.name}' must be {self.compare_op} {self.bound}: {value}"
432
+ raise ValueError(msg)
433
+
434
+ def __repr__(self):
435
+ return f"<Validator for x {self.compare_op} {self.bound}>"
436
+
437
+
438
+ def lt(val):
439
+ """
440
+ A validator that raises `ValueError` if the initializer is called with a
441
+ number larger or equal to *val*.
442
+
443
+ The validator uses `operator.lt` to compare the values.
444
+
445
+ Args:
446
+ val: Exclusive upper bound for values.
447
+
448
+ .. versionadded:: 21.3.0
449
+ """
450
+ return _NumberValidator(val, "<", operator.lt)
451
+
452
+
453
+ def le(val):
454
+ """
455
+ A validator that raises `ValueError` if the initializer is called with a
456
+ number greater than *val*.
457
+
458
+ The validator uses `operator.le` to compare the values.
459
+
460
+ Args:
461
+ val: Inclusive upper bound for values.
462
+
463
+ .. versionadded:: 21.3.0
464
+ """
465
+ return _NumberValidator(val, "<=", operator.le)
466
+
467
+
468
+ def ge(val):
469
+ """
470
+ A validator that raises `ValueError` if the initializer is called with a
471
+ number smaller than *val*.
472
+
473
+ The validator uses `operator.ge` to compare the values.
474
+
475
+ Args:
476
+ val: Inclusive lower bound for values
477
+
478
+ .. versionadded:: 21.3.0
479
+ """
480
+ return _NumberValidator(val, ">=", operator.ge)
481
+
482
+
483
+ def gt(val):
484
+ """
485
+ A validator that raises `ValueError` if the initializer is called with a
486
+ number smaller or equal to *val*.
487
+
488
+ The validator uses `operator.ge` to compare the values.
489
+
490
+ Args:
491
+ val: Exclusive lower bound for values
492
+
493
+ .. versionadded:: 21.3.0
494
+ """
495
+ return _NumberValidator(val, ">", operator.gt)
496
+
497
+
498
+ @attrs(repr=False, frozen=True, slots=True)
499
+ class _MaxLengthValidator:
500
+ max_length = attrib()
501
+
502
+ def __call__(self, inst, attr, value):
503
+ """
504
+ We use a callable class to be able to change the ``__repr__``.
505
+ """
506
+ if len(value) > self.max_length:
507
+ msg = f"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}"
508
+ raise ValueError(msg)
509
+
510
+ def __repr__(self):
511
+ return f"<max_len validator for {self.max_length}>"
512
+
513
+
514
+ def max_len(length):
515
+ """
516
+ A validator that raises `ValueError` if the initializer is called
517
+ with a string or iterable that is longer than *length*.
518
+
519
+ Args:
520
+ length (int): Maximum length of the string or iterable
521
+
522
+ .. versionadded:: 21.3.0
523
+ """
524
+ return _MaxLengthValidator(length)
525
+
526
+
527
+ @attrs(repr=False, frozen=True, slots=True)
528
+ class _MinLengthValidator:
529
+ min_length = attrib()
530
+
531
+ def __call__(self, inst, attr, value):
532
+ """
533
+ We use a callable class to be able to change the ``__repr__``.
534
+ """
535
+ if len(value) < self.min_length:
536
+ msg = f"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}"
537
+ raise ValueError(msg)
538
+
539
+ def __repr__(self):
540
+ return f"<min_len validator for {self.min_length}>"
541
+
542
+
543
+ def min_len(length):
544
+ """
545
+ A validator that raises `ValueError` if the initializer is called
546
+ with a string or iterable that is shorter than *length*.
547
+
548
+ Args:
549
+ length (int): Minimum length of the string or iterable
550
+
551
+ .. versionadded:: 22.1.0
552
+ """
553
+ return _MinLengthValidator(length)
554
+
555
+
556
+ @attrs(repr=False, slots=True, unsafe_hash=True)
557
+ class _SubclassOfValidator:
558
+ type = attrib()
559
+
560
+ def __call__(self, inst, attr, value):
561
+ """
562
+ We use a callable class to be able to change the ``__repr__``.
563
+ """
564
+ if not issubclass(value, self.type):
565
+ msg = f"'{attr.name}' must be a subclass of {self.type!r} (got {value!r})."
566
+ raise TypeError(
567
+ msg,
568
+ attr,
569
+ self.type,
570
+ value,
571
+ )
572
+
573
+ def __repr__(self):
574
+ return f"<subclass_of validator for type {self.type!r}>"
575
+
576
+
577
+ def _subclass_of(type):
578
+ """
579
+ A validator that raises a `TypeError` if the initializer is called with a
580
+ wrong type for this particular attribute (checks are performed using
581
+ `issubclass` therefore it's also valid to pass a tuple of types).
582
+
583
+ Args:
584
+ type (type | tuple[type, ...]): The type(s) to check for.
585
+
586
+ Raises:
587
+ TypeError:
588
+ With a human readable error message, the attribute (of type
589
+ `attrs.Attribute`), the expected type, and the value it got.
590
+ """
591
+ return _SubclassOfValidator(type)
592
+
593
+
594
+ @attrs(repr=False, slots=True, unsafe_hash=True)
595
+ class _NotValidator:
596
+ validator = attrib()
597
+ msg = attrib(
598
+ converter=default_if_none(
599
+ "not_ validator child '{validator!r}' "
600
+ "did not raise a captured error"
601
+ )
602
+ )
603
+ exc_types = attrib(
604
+ validator=deep_iterable(
605
+ member_validator=_subclass_of(Exception),
606
+ iterable_validator=instance_of(tuple),
607
+ ),
608
+ )
609
+
610
+ def __call__(self, inst, attr, value):
611
+ try:
612
+ self.validator(inst, attr, value)
613
+ except self.exc_types:
614
+ pass # suppress error to invert validity
615
+ else:
616
+ raise ValueError(
617
+ self.msg.format(
618
+ validator=self.validator,
619
+ exc_types=self.exc_types,
620
+ ),
621
+ attr,
622
+ self.validator,
623
+ value,
624
+ self.exc_types,
625
+ )
626
+
627
+ def __repr__(self):
628
+ return f"<not_ validator wrapping {self.validator!r}, capturing {self.exc_types!r}>"
629
+
630
+
631
+ def not_(validator, *, msg=None, exc_types=(ValueError, TypeError)):
632
+ """
633
+ A validator that wraps and logically 'inverts' the validator passed to it.
634
+ It will raise a `ValueError` if the provided validator *doesn't* raise a
635
+ `ValueError` or `TypeError` (by default), and will suppress the exception
636
+ if the provided validator *does*.
637
+
638
+ Intended to be used with existing validators to compose logic without
639
+ needing to create inverted variants, for example, ``not_(in_(...))``.
640
+
641
+ Args:
642
+ validator: A validator to be logically inverted.
643
+
644
+ msg (str):
645
+ Message to raise if validator fails. Formatted with keys
646
+ ``exc_types`` and ``validator``.
647
+
648
+ exc_types (tuple[type, ...]):
649
+ Exception type(s) to capture. Other types raised by child
650
+ validators will not be intercepted and pass through.
651
+
652
+ Raises:
653
+ ValueError:
654
+ With a human readable error message, the attribute (of type
655
+ `attrs.Attribute`), the validator that failed to raise an
656
+ exception, the value it got, and the expected exception types.
657
+
658
+ .. versionadded:: 22.2.0
659
+ """
660
+ try:
661
+ exc_types = tuple(exc_types)
662
+ except TypeError:
663
+ exc_types = (exc_types,)
664
+ return _NotValidator(validator, msg, exc_types)
665
+
666
+
667
+ @attrs(repr=False, slots=True, unsafe_hash=True)
668
+ class _OrValidator:
669
+ validators = attrib()
670
+
671
+ def __call__(self, inst, attr, value):
672
+ for v in self.validators:
673
+ try:
674
+ v(inst, attr, value)
675
+ except Exception: # noqa: BLE001, PERF203, S112
676
+ continue
677
+ else:
678
+ return
679
+
680
+ msg = f"None of {self.validators!r} satisfied for value {value!r}"
681
+ raise ValueError(msg)
682
+
683
+ def __repr__(self):
684
+ return f"<or validator wrapping {self.validators!r}>"
685
+
686
+
687
+ def or_(*validators):
688
+ """
689
+ A validator that composes multiple validators into one.
690
+
691
+ When called on a value, it runs all wrapped validators until one of them is
692
+ satisfied.
693
+
694
+ Args:
695
+ validators (~collections.abc.Iterable[typing.Callable]):
696
+ Arbitrary number of validators.
697
+
698
+ Raises:
699
+ ValueError:
700
+ If no validator is satisfied. Raised with a human-readable error
701
+ message listing all the wrapped validators and the value that
702
+ failed all of them.
703
+
704
+ .. versionadded:: 24.1.0
705
+ """
706
+ vals = []
707
+ for v in validators:
708
+ vals.extend(v.validators if isinstance(v, _OrValidator) else [v])
709
+
710
+ return _OrValidator(tuple(vals))
vllm/lib/python3.10/site-packages/attr/validators.pyi ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import UnionType
2
+ from typing import (
3
+ Any,
4
+ AnyStr,
5
+ Callable,
6
+ Container,
7
+ ContextManager,
8
+ Iterable,
9
+ Mapping,
10
+ Match,
11
+ Pattern,
12
+ TypeVar,
13
+ overload,
14
+ )
15
+
16
+ from attrs import _ValidatorType
17
+ from attrs import _ValidatorArgType
18
+
19
+ _T = TypeVar("_T")
20
+ _T1 = TypeVar("_T1")
21
+ _T2 = TypeVar("_T2")
22
+ _T3 = TypeVar("_T3")
23
+ _I = TypeVar("_I", bound=Iterable)
24
+ _K = TypeVar("_K")
25
+ _V = TypeVar("_V")
26
+ _M = TypeVar("_M", bound=Mapping)
27
+
28
+ def set_disabled(run: bool) -> None: ...
29
+ def get_disabled() -> bool: ...
30
+ def disabled() -> ContextManager[None]: ...
31
+
32
+ # To be more precise on instance_of use some overloads.
33
+ # If there are more than 3 items in the tuple then we fall back to Any
34
+ @overload
35
+ def instance_of(type: type[_T]) -> _ValidatorType[_T]: ...
36
+ @overload
37
+ def instance_of(type: tuple[type[_T]]) -> _ValidatorType[_T]: ...
38
+ @overload
39
+ def instance_of(
40
+ type: tuple[type[_T1], type[_T2]],
41
+ ) -> _ValidatorType[_T1 | _T2]: ...
42
+ @overload
43
+ def instance_of(
44
+ type: tuple[type[_T1], type[_T2], type[_T3]],
45
+ ) -> _ValidatorType[_T1 | _T2 | _T3]: ...
46
+ @overload
47
+ def instance_of(type: tuple[type, ...]) -> _ValidatorType[Any]: ...
48
+ @overload
49
+ def instance_of(type: UnionType) -> _ValidatorType[Any]: ...
50
+ def optional(
51
+ validator: (
52
+ _ValidatorType[_T]
53
+ | list[_ValidatorType[_T]]
54
+ | tuple[_ValidatorType[_T]]
55
+ ),
56
+ ) -> _ValidatorType[_T | None]: ...
57
+ def in_(options: Container[_T]) -> _ValidatorType[_T]: ...
58
+ def and_(*validators: _ValidatorType[_T]) -> _ValidatorType[_T]: ...
59
+ def matches_re(
60
+ regex: Pattern[AnyStr] | AnyStr,
61
+ flags: int = ...,
62
+ func: Callable[[AnyStr, AnyStr, int], Match[AnyStr] | None] | None = ...,
63
+ ) -> _ValidatorType[AnyStr]: ...
64
+ def deep_iterable(
65
+ member_validator: _ValidatorArgType[_T],
66
+ iterable_validator: _ValidatorType[_I] | None = ...,
67
+ ) -> _ValidatorType[_I]: ...
68
+ def deep_mapping(
69
+ key_validator: _ValidatorType[_K],
70
+ value_validator: _ValidatorType[_V],
71
+ mapping_validator: _ValidatorType[_M] | None = ...,
72
+ ) -> _ValidatorType[_M]: ...
73
+ def is_callable() -> _ValidatorType[_T]: ...
74
+ def lt(val: _T) -> _ValidatorType[_T]: ...
75
+ def le(val: _T) -> _ValidatorType[_T]: ...
76
+ def ge(val: _T) -> _ValidatorType[_T]: ...
77
+ def gt(val: _T) -> _ValidatorType[_T]: ...
78
+ def max_len(length: int) -> _ValidatorType[_T]: ...
79
+ def min_len(length: int) -> _ValidatorType[_T]: ...
80
+ def not_(
81
+ validator: _ValidatorType[_T],
82
+ *,
83
+ msg: str | None = None,
84
+ exc_types: type[Exception] | Iterable[type[Exception]] = ...,
85
+ ) -> _ValidatorType[_T]: ...
86
+ def or_(*validators: _ValidatorType[_T]) -> _ValidatorType[_T]: ...
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/acero/api.h ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // NOTE: API is EXPERIMENTAL and will change without going through a
19
+ // deprecation cycle
20
+
21
+ #pragma once
22
+
23
+ /// \defgroup acero-api Utilities for creating and executing execution plans
24
+ /// @{
25
+ /// @}
26
+
27
+ /// \defgroup acero-nodes Options classes for the various exec nodes
28
+ /// @{
29
+ /// @}
30
+
31
+ #include "arrow/acero/exec_plan.h"
32
+ #include "arrow/acero/options.h"
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/acero/hash_join_dict.h ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <memory>
21
+ #include <unordered_map>
22
+
23
+ #include "arrow/acero/schema_util.h"
24
+ #include "arrow/compute/exec.h"
25
+ #include "arrow/compute/row/row_encoder_internal.h"
26
+ #include "arrow/result.h"
27
+ #include "arrow/status.h"
28
+ #include "arrow/type.h"
29
+
30
+ // This file contains hash join logic related to handling of dictionary encoded key
31
+ // columns.
32
+ //
33
+ // A key column from probe side of the join can be matched against a key column from build
34
+ // side of the join, as long as the underlying value types are equal. That means that:
35
+ // - both scalars and arrays can be used and even mixed in the same column
36
+ // - dictionary column can be matched against non-dictionary column if underlying value
37
+ // types are equal
38
+ // - dictionary column can be matched against dictionary column with a different index
39
+ // type, and potentially using a different dictionary, if underlying value types are equal
40
+ //
41
+ // We currently require in hash join that for all dictionary encoded columns, the same
42
+ // dictionary is used in all input exec batches.
43
+ //
44
+ // In order to allow matching columns with different dictionaries, different dictionary
45
+ // index types, and dictionary key against non-dictionary key, internally comparisons will
46
+ // be evaluated after remapping values on both sides of the join to a common
47
+ // representation (which will be called "unified representation"). This common
48
+ // representation is a column of int32() type (not a dictionary column). It represents an
49
+ // index in the unified dictionary computed for the (only) dictionary present on build
50
+ // side (an empty dictionary is still created for an empty build side). Null value is
51
+ // always represented in this common representation as null int32 value, unified
52
+ // dictionary will never contain a null value (so there is no ambiguity of representing
53
+ // nulls as either index to a null entry in the dictionary or null index).
54
+ //
55
+ // Unified dictionary represents values present on build side. There may be values on
56
+ // probe side that are not present in it. All such values, that are not null, are mapped
57
+ // in the common representation to a special constant kMissingValueId.
58
+ //
59
+
60
+ namespace arrow {
61
+
62
+ using compute::ExecBatch;
63
+ using compute::ExecContext;
64
+ using compute::internal::RowEncoder;
65
+
66
+ namespace acero {
67
+
68
+ /// Helper class with operations that are stateless and common to processing of dictionary
69
+ /// keys on both build and probe side.
70
+ class HashJoinDictUtil {
71
+ public:
72
+ // Null values in unified representation are always represented as null that has
73
+ // corresponding integer set to this constant
74
+ static constexpr int32_t kNullId = 0;
75
+ // Constant representing a value, that is not null, missing on the build side, in
76
+ // unified representation.
77
+ static constexpr int32_t kMissingValueId = -1;
78
+
79
+ // Check if data types of corresponding pair of key column on build and probe side are
80
+ // compatible
81
+ static bool KeyDataTypesValid(const std::shared_ptr<DataType>& probe_data_type,
82
+ const std::shared_ptr<DataType>& build_data_type);
83
+
84
+ // Input must be dictionary array or dictionary scalar.
85
+ // A precomputed and provided here lookup table in the form of int32() array will be
86
+ // used to remap input indices to unified representation.
87
+ //
88
+ static Result<std::shared_ptr<ArrayData>> IndexRemapUsingLUT(
89
+ ExecContext* ctx, const Datum& indices, int64_t batch_length,
90
+ const std::shared_ptr<ArrayData>& map_array,
91
+ const std::shared_ptr<DataType>& data_type);
92
+
93
+ // Return int32() array that contains indices of input dictionary array or scalar after
94
+ // type casting.
95
+ static Result<std::shared_ptr<ArrayData>> ConvertToInt32(
96
+ const std::shared_ptr<DataType>& from_type, const Datum& input,
97
+ int64_t batch_length, ExecContext* ctx);
98
+
99
+ // Return an array that contains elements of input int32() array after casting to a
100
+ // given integer type. This is used for mapping unified representation stored in the
101
+ // hash table on build side back to original input data type of hash join, when
102
+ // outputting hash join results to parent exec node.
103
+ //
104
+ static Result<std::shared_ptr<ArrayData>> ConvertFromInt32(
105
+ const std::shared_ptr<DataType>& to_type, const Datum& input, int64_t batch_length,
106
+ ExecContext* ctx);
107
+
108
+ // Return dictionary referenced in either dictionary array or dictionary scalar
109
+ static std::shared_ptr<Array> ExtractDictionary(const Datum& data);
110
+ };
111
+
112
+ /// Implements processing of dictionary arrays/scalars in key columns on the build side of
113
+ /// a hash join.
114
+ /// Each instance of this class corresponds to a single column and stores and
115
+ /// processes only the information related to that column.
116
+ /// Const methods are thread-safe, non-const methods are not (the caller must make sure
117
+ /// that only one thread at any time will access them).
118
+ ///
119
+ class HashJoinDictBuild {
120
+ public:
121
+ // Returns true if the key column (described in input by its data type) requires any
122
+ // pre- or post-processing related to handling dictionaries.
123
+ //
124
+ static bool KeyNeedsProcessing(const std::shared_ptr<DataType>& build_data_type) {
125
+ return (build_data_type->id() == Type::DICTIONARY);
126
+ }
127
+
128
+ // Data type of unified representation
129
+ static std::shared_ptr<DataType> DataTypeAfterRemapping() { return int32(); }
130
+
131
+ // Should be called only once in hash join, before processing any build or probe
132
+ // batches.
133
+ //
134
+ // Takes a pointer to the dictionary for a corresponding key column on the build side as
135
+ // an input. If the build side is empty, it still needs to be called, but with
136
+ // dictionary pointer set to null.
137
+ //
138
+ // Currently it is required that all input batches on build side share the same
139
+ // dictionary. For each input batch during its pre-processing, dictionary will be
140
+ // checked and error will be returned if it is different then the one provided in the
141
+ // call to this method.
142
+ //
143
+ // Unifies the dictionary. The order of the values is still preserved.
144
+ // Null and duplicate entries are removed. If the dictionary is already unified, its
145
+ // copy will be produced and stored within this class.
146
+ //
147
+ // Prepares the mapping from ids within original dictionary to the ids in the resulting
148
+ // dictionary. This is used later on to pre-process (map to unified representation) key
149
+ // column on build side.
150
+ //
151
+ // Prepares the reverse mapping (in the form of hash table) from values to the ids in
152
+ // the resulting dictionary. This will be used later on to pre-process (map to unified
153
+ // representation) key column on probe side. Values on probe side that are not present
154
+ // in the original dictionary will be mapped to a special constant kMissingValueId. The
155
+ // exception is made for nulls, which get always mapped to nulls (both when null is
156
+ // represented as a dictionary id pointing to a null and a null dictionary id).
157
+ //
158
+ Status Init(ExecContext* ctx, std::shared_ptr<Array> dictionary,
159
+ std::shared_ptr<DataType> index_type, std::shared_ptr<DataType> value_type);
160
+
161
+ // Remap array or scalar values into unified representation (array of int32()).
162
+ // Outputs kMissingValueId if input value is not found in the unified dictionary.
163
+ // Outputs null for null input value (with corresponding data set to kNullId).
164
+ //
165
+ Result<std::shared_ptr<ArrayData>> RemapInputValues(ExecContext* ctx,
166
+ const Datum& values,
167
+ int64_t batch_length) const;
168
+
169
+ // Remap dictionary array or dictionary scalar on build side to unified representation.
170
+ // Dictionary referenced in the input must match the dictionary that was
171
+ // given during initialization.
172
+ // The output is a dictionary array that references unified dictionary.
173
+ //
174
+ Result<std::shared_ptr<ArrayData>> RemapInput(
175
+ ExecContext* ctx, const Datum& indices, int64_t batch_length,
176
+ const std::shared_ptr<DataType>& data_type) const;
177
+
178
+ // Outputs dictionary array referencing unified dictionary, given an array with 32-bit
179
+ // ids.
180
+ // Used to post-process values looked up in a hash table on build side of the hash join
181
+ // before outputting to the parent exec node.
182
+ //
183
+ Result<std::shared_ptr<ArrayData>> RemapOutput(const ArrayData& indices32Bit,
184
+ ExecContext* ctx) const;
185
+
186
+ // Release shared pointers and memory
187
+ void CleanUp();
188
+
189
+ private:
190
+ // Data type of dictionary ids for the input dictionary on build side
191
+ std::shared_ptr<DataType> index_type_;
192
+ // Data type of values for the input dictionary on build side
193
+ std::shared_ptr<DataType> value_type_;
194
+ // Mapping from (encoded as string) values to the ids in unified dictionary
195
+ std::unordered_map<std::string, int32_t> hash_table_;
196
+ // Mapping from input dictionary ids to unified dictionary ids
197
+ std::shared_ptr<ArrayData> remapped_ids_;
198
+ // Input dictionary
199
+ std::shared_ptr<Array> dictionary_;
200
+ // Unified dictionary
201
+ std::shared_ptr<ArrayData> unified_dictionary_;
202
+ };
203
+
204
+ /// Implements processing of dictionary arrays/scalars in key columns on the probe side of
205
+ /// a hash join.
206
+ /// Each instance of this class corresponds to a single column and stores and
207
+ /// processes only the information related to that column.
208
+ /// It is not thread-safe - every participating thread should use its own instance of
209
+ /// this class.
210
+ ///
211
+ class HashJoinDictProbe {
212
+ public:
213
+ static bool KeyNeedsProcessing(const std::shared_ptr<DataType>& probe_data_type,
214
+ const std::shared_ptr<DataType>& build_data_type);
215
+
216
+ // Data type of the result of remapping input key column.
217
+ //
218
+ // The result of remapping is what is used in hash join for matching keys on build and
219
+ // probe side. The exact data types may be different, as described below, and therefore
220
+ // a common representation is needed for simplifying comparisons of pairs of keys on
221
+ // both sides.
222
+ //
223
+ // We support matching key that is of non-dictionary type with key that is of dictionary
224
+ // type, as long as the underlying value types are equal. We support matching when both
225
+ // keys are of dictionary type, regardless whether underlying dictionary index types are
226
+ // the same or not.
227
+ //
228
+ static std::shared_ptr<DataType> DataTypeAfterRemapping(
229
+ const std::shared_ptr<DataType>& build_data_type);
230
+
231
+ // Should only be called if KeyNeedsProcessing method returns true for a pair of
232
+ // corresponding key columns from build and probe side.
233
+ // Converts values in order to match the common representation for
234
+ // both build and probe side used in hash table comparison.
235
+ // Supports arrays and scalars as input.
236
+ // Argument opt_build_side should be null if dictionary key on probe side is matched
237
+ // with non-dictionary key on build side.
238
+ //
239
+ Result<std::shared_ptr<ArrayData>> RemapInput(
240
+ const HashJoinDictBuild* opt_build_side, const Datum& data, int64_t batch_length,
241
+ const std::shared_ptr<DataType>& probe_data_type,
242
+ const std::shared_ptr<DataType>& build_data_type, ExecContext* ctx);
243
+
244
+ void CleanUp();
245
+
246
+ private:
247
+ // May be null if probe side key is non-dictionary. Otherwise it is used to verify that
248
+ // only a single dictionary is referenced in exec batch on probe side of hash join.
249
+ std::shared_ptr<Array> dictionary_;
250
+ // Mapping from dictionary on probe side of hash join (if it is used) to unified
251
+ // representation.
252
+ std::shared_ptr<ArrayData> remapped_ids_;
253
+ // Encoder of key columns that uses unified representation instead of original data type
254
+ // for key columns that need to use it (have dictionaries on either side of the join).
255
+ RowEncoder encoder_;
256
+ };
257
+
258
+ // Encapsulates dictionary handling logic for build side of hash join.
259
+ //
260
+ class HashJoinDictBuildMulti {
261
+ public:
262
+ Status Init(const SchemaProjectionMaps<HashJoinProjection>& proj_map,
263
+ const ExecBatch* opt_non_empty_batch, ExecContext* ctx);
264
+ static void InitEncoder(const SchemaProjectionMaps<HashJoinProjection>& proj_map,
265
+ RowEncoder* encoder, ExecContext* ctx);
266
+ Status EncodeBatch(size_t thread_index,
267
+ const SchemaProjectionMaps<HashJoinProjection>& proj_map,
268
+ const ExecBatch& batch, RowEncoder* encoder, ExecContext* ctx) const;
269
+ Status PostDecode(const SchemaProjectionMaps<HashJoinProjection>& proj_map,
270
+ ExecBatch* decoded_key_batch, ExecContext* ctx);
271
+ const HashJoinDictBuild& get_dict_build(int icol) const { return remap_imp_[icol]; }
272
+
273
+ private:
274
+ std::vector<bool> needs_remap_;
275
+ std::vector<HashJoinDictBuild> remap_imp_;
276
+ };
277
+
278
+ // Encapsulates dictionary handling logic for probe side of hash join
279
+ //
280
+ class HashJoinDictProbeMulti {
281
+ public:
282
+ void Init(size_t num_threads);
283
+ bool BatchRemapNeeded(size_t thread_index,
284
+ const SchemaProjectionMaps<HashJoinProjection>& proj_map_probe,
285
+ const SchemaProjectionMaps<HashJoinProjection>& proj_map_build,
286
+ ExecContext* ctx);
287
+ Status EncodeBatch(size_t thread_index,
288
+ const SchemaProjectionMaps<HashJoinProjection>& proj_map_probe,
289
+ const SchemaProjectionMaps<HashJoinProjection>& proj_map_build,
290
+ const HashJoinDictBuildMulti& dict_build, const ExecBatch& batch,
291
+ RowEncoder** out_encoder, ExecBatch* opt_out_key_batch,
292
+ ExecContext* ctx);
293
+
294
+ private:
295
+ void InitLocalStateIfNeeded(
296
+ size_t thread_index, const SchemaProjectionMaps<HashJoinProjection>& proj_map_probe,
297
+ const SchemaProjectionMaps<HashJoinProjection>& proj_map_build, ExecContext* ctx);
298
+ static void InitEncoder(const SchemaProjectionMaps<HashJoinProjection>& proj_map_probe,
299
+ const SchemaProjectionMaps<HashJoinProjection>& proj_map_build,
300
+ RowEncoder* encoder, ExecContext* ctx);
301
+ struct ThreadLocalState {
302
+ bool is_initialized;
303
+ // Whether any key column needs remapping (because of dictionaries used) before doing
304
+ // join hash table lookups
305
+ bool any_needs_remap;
306
+ // Whether each key column needs remapping before doing join hash table lookups
307
+ std::vector<bool> needs_remap;
308
+ std::vector<HashJoinDictProbe> remap_imp;
309
+ // Encoder of key columns that uses unified representation instead of original data
310
+ // type for key columns that need to use it (have dictionaries on either side of the
311
+ // join).
312
+ RowEncoder post_remap_encoder;
313
+ };
314
+ std::vector<ThreadLocalState> local_states_;
315
+ };
316
+
317
+ } // namespace acero
318
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/acero/map_node.h ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <functional>
22
+ #include <memory>
23
+ #include <vector>
24
+
25
+ #include "arrow/acero/exec_plan.h"
26
+ #include "arrow/acero/util.h"
27
+ #include "arrow/acero/visibility.h"
28
+ #include "arrow/compute/type_fwd.h"
29
+ #include "arrow/status.h"
30
+ #include "arrow/type_fwd.h"
31
+ #include "arrow/util/cancel.h"
32
+ #include "arrow/util/type_fwd.h"
33
+
34
+ namespace arrow {
35
+ namespace acero {
36
+
37
+ /// A utility base class for simple exec nodes with one input
38
+ ///
39
+ /// Pause/Resume Producing are forwarded appropriately
40
+ /// There is nothing to do in StopProducingImpl
41
+ ///
42
+ /// An AtomicCounter is used to keep track of when all data has arrived. When it
43
+ /// has the Finish() method will be invoked
44
+ class ARROW_ACERO_EXPORT MapNode : public ExecNode, public TracedNode {
45
+ public:
46
+ MapNode(ExecPlan* plan, std::vector<ExecNode*> inputs,
47
+ std::shared_ptr<Schema> output_schema);
48
+
49
+ Status InputFinished(ExecNode* input, int total_batches) override;
50
+
51
+ Status StartProducing() override;
52
+
53
+ void PauseProducing(ExecNode* output, int32_t counter) override;
54
+
55
+ void ResumeProducing(ExecNode* output, int32_t counter) override;
56
+
57
+ Status InputReceived(ExecNode* input, ExecBatch batch) override;
58
+
59
+ const Ordering& ordering() const override;
60
+
61
+ protected:
62
+ Status StopProducingImpl() override;
63
+
64
+ /// Transform a batch
65
+ ///
66
+ /// The output batch will have the same guarantee as the input batch
67
+ /// If this was the last batch this call may trigger Finish()
68
+ virtual Result<ExecBatch> ProcessBatch(ExecBatch batch) = 0;
69
+
70
+ /// Function called after all data has been received
71
+ ///
72
+ /// By default this does nothing. Override this to provide a custom implementation.
73
+ virtual void Finish();
74
+
75
+ protected:
76
+ // Counter for the number of batches received
77
+ AtomicCounter input_counter_;
78
+ };
79
+
80
+ } // namespace acero
81
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/acero/order_by_impl.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <functional>
21
+ #include <memory>
22
+ #include <vector>
23
+
24
+ #include "arrow/acero/options.h"
25
+ #include "arrow/record_batch.h"
26
+ #include "arrow/result.h"
27
+ #include "arrow/status.h"
28
+ #include "arrow/type.h"
29
+
30
+ namespace arrow {
31
+
32
+ using compute::ExecContext;
33
+
34
+ namespace acero {
35
+
36
+ class OrderByImpl {
37
+ public:
38
+ virtual ~OrderByImpl() = default;
39
+
40
+ virtual void InputReceived(const std::shared_ptr<RecordBatch>& batch) = 0;
41
+
42
+ virtual Result<Datum> DoFinish() = 0;
43
+
44
+ virtual std::string ToString() const = 0;
45
+
46
+ static Result<std::unique_ptr<OrderByImpl>> MakeSort(
47
+ ExecContext* ctx, const std::shared_ptr<Schema>& output_schema,
48
+ const SortOptions& options);
49
+
50
+ static Result<std::unique_ptr<OrderByImpl>> MakeSelectK(
51
+ ExecContext* ctx, const std::shared_ptr<Schema>& output_schema,
52
+ const SelectKOptions& options);
53
+ };
54
+
55
+ } // namespace acero
56
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/acero/query_context.h ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+ #pragma once
18
+
19
+ #include <string_view>
20
+
21
+ #include "arrow/acero/exec_plan.h"
22
+ #include "arrow/acero/task_util.h"
23
+ #include "arrow/acero/util.h"
24
+ #include "arrow/compute/exec.h"
25
+ #include "arrow/io/interfaces.h"
26
+ #include "arrow/util/async_util.h"
27
+ #include "arrow/util/type_fwd.h"
28
+
29
+ namespace arrow {
30
+
31
+ using compute::default_exec_context;
32
+ using io::IOContext;
33
+
34
+ namespace acero {
35
+
36
+ class ARROW_ACERO_EXPORT QueryContext {
37
+ public:
38
+ QueryContext(QueryOptions opts = {},
39
+ ExecContext exec_context = *default_exec_context());
40
+
41
+ Status Init(arrow::util::AsyncTaskScheduler* scheduler);
42
+
43
+ const ::arrow::internal::CpuInfo* cpu_info() const;
44
+ int64_t hardware_flags() const;
45
+ const QueryOptions& options() const { return options_; }
46
+ MemoryPool* memory_pool() const { return exec_context_.memory_pool(); }
47
+ ::arrow::internal::Executor* executor() const { return exec_context_.executor(); }
48
+ ExecContext* exec_context() { return &exec_context_; }
49
+ IOContext* io_context() { return &io_context_; }
50
+ TaskScheduler* scheduler() { return task_scheduler_.get(); }
51
+ arrow::util::AsyncTaskScheduler* async_scheduler() { return async_scheduler_; }
52
+
53
+ size_t GetThreadIndex();
54
+ size_t max_concurrency() const;
55
+
56
+ /// \brief Start an external task
57
+ ///
58
+ /// This should be avoided if possible. It is kept in for now for legacy
59
+ /// purposes. This should be called before the external task is started. If
60
+ /// a valid future is returned then it should be marked complete when the
61
+ /// external task has finished.
62
+ ///
63
+ /// \param name A name to give the task for traceability and debugging
64
+ ///
65
+ /// \return an invalid future if the plan has already ended, otherwise this
66
+ /// returns a future that must be completed when the external task
67
+ /// finishes.
68
+ Result<Future<>> BeginExternalTask(std::string_view name);
69
+
70
+ /// \brief Add a single function as a task to the query's task group
71
+ /// on the compute threadpool.
72
+ ///
73
+ /// \param fn The task to run. Takes no arguments and returns a Status.
74
+ /// \param name A name to give the task for traceability and debugging
75
+ void ScheduleTask(std::function<Status()> fn, std::string_view name);
76
+ /// \brief Add a single function as a task to the query's task group
77
+ /// on the compute threadpool.
78
+ ///
79
+ /// \param fn The task to run. Takes the thread index and returns a Status.
80
+ /// \param name A name to give the task for traceability and debugging
81
+ void ScheduleTask(std::function<Status(size_t)> fn, std::string_view name);
82
+ /// \brief Add a single function as a task to the query's task group on
83
+ /// the IO thread pool
84
+ ///
85
+ /// \param fn The task to run. Returns a status.
86
+ /// \param name A name to give the task for traceability and debugging
87
+ void ScheduleIOTask(std::function<Status()> fn, std::string_view name);
88
+
89
+ // Register/Start TaskGroup is a way of performing a "Parallel For" pattern:
90
+ // - The task function takes the thread index and the index of the task
91
+ // - The on_finished function takes the thread index
92
+ // Returns an integer ID that will be used to reference the task group in
93
+ // StartTaskGroup. At runtime, call StartTaskGroup with the ID and the number of times
94
+ // you'd like the task to be executed. The need to register a task group before use will
95
+ // be removed after we rewrite the scheduler.
96
+ /// \brief Register a "parallel for" task group with the scheduler
97
+ ///
98
+ /// \param task The function implementing the task. Takes the thread_index and
99
+ /// the task index.
100
+ /// \param on_finished The function that gets run once all tasks have been completed.
101
+ /// Takes the thread_index.
102
+ ///
103
+ /// Must be called inside of ExecNode::Init.
104
+ int RegisterTaskGroup(std::function<Status(size_t, int64_t)> task,
105
+ std::function<Status(size_t)> on_finished);
106
+
107
+ /// \brief Start the task group with the specified ID. This can only
108
+ /// be called once per task_group_id.
109
+ ///
110
+ /// \param task_group_id The ID of the task group to run
111
+ /// \param num_tasks The number of times to run the task
112
+ Status StartTaskGroup(int task_group_id, int64_t num_tasks);
113
+
114
+ // This is an RAII class for keeping track of in-flight file IO. Useful for getting
115
+ // an estimate of memory use, and how much memory we expect to be freed soon.
116
+ // Returned by ReportTempFileIO.
117
+ struct [[nodiscard]] TempFileIOMark {
118
+ QueryContext* ctx_;
119
+ size_t bytes_;
120
+
121
+ TempFileIOMark(QueryContext* ctx, size_t bytes) : ctx_(ctx), bytes_(bytes) {
122
+ ctx_->in_flight_bytes_to_disk_.fetch_add(bytes_, std::memory_order_acquire);
123
+ }
124
+
125
+ ARROW_DISALLOW_COPY_AND_ASSIGN(TempFileIOMark);
126
+
127
+ ~TempFileIOMark() {
128
+ ctx_->in_flight_bytes_to_disk_.fetch_sub(bytes_, std::memory_order_release);
129
+ }
130
+ };
131
+
132
+ TempFileIOMark ReportTempFileIO(size_t bytes) { return {this, bytes}; }
133
+
134
+ size_t GetCurrentTempFileIO() { return in_flight_bytes_to_disk_.load(); }
135
+
136
+ private:
137
+ QueryOptions options_;
138
+ // To be replaced with Acero-specific context once scheduler is done and
139
+ // we don't need ExecContext for kernels
140
+ ExecContext exec_context_;
141
+ IOContext io_context_;
142
+
143
+ arrow::util::AsyncTaskScheduler* async_scheduler_ = NULLPTR;
144
+ std::unique_ptr<TaskScheduler> task_scheduler_ = TaskScheduler::Make();
145
+
146
+ ThreadIndexer thread_indexer_;
147
+
148
+ std::atomic<size_t> in_flight_bytes_to_disk_{0};
149
+ };
150
+ } // namespace acero
151
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/acero/task_util.h ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <atomic>
21
+ #include <cstdint>
22
+ #include <functional>
23
+ #include <vector>
24
+
25
+ #include "arrow/acero/visibility.h"
26
+ #include "arrow/status.h"
27
+ #include "arrow/util/config.h"
28
+ #include "arrow/util/logging.h"
29
+
30
+ namespace arrow {
31
+ namespace acero {
32
+
33
+ // Atomic value surrounded by padding bytes to avoid cache line invalidation
34
+ // whenever it is modified by a concurrent thread on a different CPU core.
35
+ //
36
+ template <typename T>
37
+ class AtomicWithPadding {
38
+ private:
39
+ static constexpr int kCacheLineSize = 64;
40
+ uint8_t padding_before[kCacheLineSize];
41
+
42
+ public:
43
+ std::atomic<T> value;
44
+
45
+ private:
46
+ uint8_t padding_after[kCacheLineSize];
47
+ };
48
+
49
+ // Used for asynchronous execution of operations that can be broken into
50
+ // a fixed number of symmetric tasks that can be executed concurrently.
51
+ //
52
+ // Implements priorities between multiple such operations, called task groups.
53
+ //
54
+ // Allows to specify the maximum number of in-flight tasks at any moment.
55
+ //
56
+ // Also allows for executing next pending tasks immediately using a caller thread.
57
+ //
58
+ class ARROW_ACERO_EXPORT TaskScheduler {
59
+ public:
60
+ using TaskImpl = std::function<Status(size_t, int64_t)>;
61
+ using TaskGroupContinuationImpl = std::function<Status(size_t)>;
62
+ using ScheduleImpl = std::function<Status(TaskGroupContinuationImpl)>;
63
+ using AbortContinuationImpl = std::function<void()>;
64
+
65
+ virtual ~TaskScheduler() = default;
66
+
67
+ // Order in which task groups are registered represents priorities of their tasks
68
+ // (the first group has the highest priority).
69
+ //
70
+ // Returns task group identifier that is used to request operations on the task group.
71
+ virtual int RegisterTaskGroup(TaskImpl task_impl,
72
+ TaskGroupContinuationImpl cont_impl) = 0;
73
+
74
+ virtual void RegisterEnd() = 0;
75
+
76
+ // total_num_tasks may be zero, in which case task group continuation will be executed
77
+ // immediately
78
+ virtual Status StartTaskGroup(size_t thread_id, int group_id,
79
+ int64_t total_num_tasks) = 0;
80
+
81
+ // Execute given number of tasks immediately using caller thread
82
+ virtual Status ExecuteMore(size_t thread_id, int num_tasks_to_execute,
83
+ bool execute_all) = 0;
84
+
85
+ // Begin scheduling tasks using provided callback and
86
+ // the limit on the number of in-flight tasks at any moment.
87
+ //
88
+ // Scheduling will continue as long as there are waiting tasks.
89
+ //
90
+ // It will automatically resume whenever new task group gets started.
91
+ virtual Status StartScheduling(size_t thread_id, ScheduleImpl schedule_impl,
92
+ int num_concurrent_tasks, bool use_sync_execution) = 0;
93
+
94
+ // Abort scheduling and execution.
95
+ // Used in case of being notified about unrecoverable error for the entire query.
96
+ virtual void Abort(AbortContinuationImpl impl) = 0;
97
+
98
+ static std::unique_ptr<TaskScheduler> Make();
99
+ };
100
+
101
+ } // namespace acero
102
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_primitive.h ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Array accessor types for primitive/C-type-based arrays, such as numbers,
19
+ // boolean, and temporal types.
20
+
21
+ #pragma once
22
+
23
+ #include <cstdint>
24
+ #include <memory>
25
+
26
+ #include "arrow/array/array_base.h"
27
+ #include "arrow/array/data.h"
28
+ #include "arrow/stl_iterator.h"
29
+ #include "arrow/type.h"
30
+ #include "arrow/type_fwd.h" // IWYU pragma: export
31
+ #include "arrow/type_traits.h"
32
+ #include "arrow/util/bit_util.h"
33
+ #include "arrow/util/macros.h"
34
+ #include "arrow/util/visibility.h"
35
+
36
+ namespace arrow {
37
+
38
+ /// Concrete Array class for boolean data
39
+ class ARROW_EXPORT BooleanArray : public PrimitiveArray {
40
+ public:
41
+ using TypeClass = BooleanType;
42
+ using IteratorType = stl::ArrayIterator<BooleanArray>;
43
+
44
+ explicit BooleanArray(const std::shared_ptr<ArrayData>& data);
45
+
46
+ BooleanArray(int64_t length, const std::shared_ptr<Buffer>& data,
47
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
48
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
49
+
50
+ bool Value(int64_t i) const {
51
+ return bit_util::GetBit(reinterpret_cast<const uint8_t*>(raw_values_),
52
+ i + data_->offset);
53
+ }
54
+
55
+ bool GetView(int64_t i) const { return Value(i); }
56
+
57
+ std::optional<bool> operator[](int64_t i) const { return *IteratorType(*this, i); }
58
+
59
+ /// \brief Return the number of false (0) values among the valid
60
+ /// values. Result is not cached.
61
+ int64_t false_count() const;
62
+
63
+ /// \brief Return the number of true (1) values among the valid
64
+ /// values. Result is not cached.
65
+ int64_t true_count() const;
66
+
67
+ IteratorType begin() const { return IteratorType(*this); }
68
+
69
+ IteratorType end() const { return IteratorType(*this, length()); }
70
+
71
+ protected:
72
+ using PrimitiveArray::PrimitiveArray;
73
+ };
74
+
75
+ /// \addtogroup numeric-arrays
76
+ ///
77
+ /// @{
78
+
79
+ /// \brief Concrete Array class for numeric data with a corresponding C type
80
+ ///
81
+ /// This class is templated on the corresponding DataType subclass for the
82
+ /// given data, for example NumericArray<Int8Type> or NumericArray<Date32Type>.
83
+ ///
84
+ /// Note that convenience aliases are available for all accepted types
85
+ /// (for example Int8Array for NumericArray<Int8Type>).
86
+ template <typename TYPE>
87
+ class NumericArray : public PrimitiveArray {
88
+ public:
89
+ using TypeClass = TYPE;
90
+ using value_type = typename TypeClass::c_type;
91
+ using IteratorType = stl::ArrayIterator<NumericArray<TYPE>>;
92
+
93
+ explicit NumericArray(const std::shared_ptr<ArrayData>& data) { SetData(data); }
94
+
95
+ // Only enable this constructor without a type argument for types without additional
96
+ // metadata
97
+ template <typename T1 = TYPE>
98
+ NumericArray(enable_if_parameter_free<T1, int64_t> length,
99
+ const std::shared_ptr<Buffer>& data,
100
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
101
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0) {
102
+ SetData(ArrayData::Make(TypeTraits<T1>::type_singleton(), length, {null_bitmap, data},
103
+ null_count, offset));
104
+ }
105
+
106
+ const value_type* raw_values() const { return values_; }
107
+
108
+ value_type Value(int64_t i) const { return values_[i]; }
109
+
110
+ // For API compatibility with BinaryArray etc.
111
+ value_type GetView(int64_t i) const { return values_[i]; }
112
+
113
+ std::optional<value_type> operator[](int64_t i) const {
114
+ return *IteratorType(*this, i);
115
+ }
116
+
117
+ IteratorType begin() const { return IteratorType(*this); }
118
+
119
+ IteratorType end() const { return IteratorType(*this, length()); }
120
+
121
+ protected:
122
+ using PrimitiveArray::PrimitiveArray;
123
+
124
+ void SetData(const std::shared_ptr<ArrayData>& data) {
125
+ this->PrimitiveArray::SetData(data);
126
+ values_ = raw_values_
127
+ ? (reinterpret_cast<const value_type*>(raw_values_) + data_->offset)
128
+ : NULLPTR;
129
+ }
130
+
131
+ const value_type* values_;
132
+ };
133
+
134
+ /// DayTimeArray
135
+ /// ---------------------
136
+ /// \brief Array of Day and Millisecond values.
137
+ class ARROW_EXPORT DayTimeIntervalArray : public PrimitiveArray {
138
+ public:
139
+ using TypeClass = DayTimeIntervalType;
140
+ using IteratorType = stl::ArrayIterator<DayTimeIntervalArray>;
141
+
142
+ explicit DayTimeIntervalArray(const std::shared_ptr<ArrayData>& data);
143
+
144
+ DayTimeIntervalArray(const std::shared_ptr<DataType>& type, int64_t length,
145
+ const std::shared_ptr<Buffer>& data,
146
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
147
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
148
+
149
+ DayTimeIntervalArray(int64_t length, const std::shared_ptr<Buffer>& data,
150
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
151
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
152
+
153
+ TypeClass::DayMilliseconds GetValue(int64_t i) const;
154
+ TypeClass::DayMilliseconds Value(int64_t i) const { return GetValue(i); }
155
+
156
+ // For compatibility with Take kernel.
157
+ TypeClass::DayMilliseconds GetView(int64_t i) const { return GetValue(i); }
158
+
159
+ IteratorType begin() const { return IteratorType(*this); }
160
+
161
+ IteratorType end() const { return IteratorType(*this, length()); }
162
+
163
+ std::optional<TypeClass::DayMilliseconds> operator[](int64_t i) const {
164
+ return *IteratorType(*this, i);
165
+ }
166
+
167
+ int32_t byte_width() const { return sizeof(TypeClass::DayMilliseconds); }
168
+
169
+ const uint8_t* raw_values() const { return raw_values_ + data_->offset * byte_width(); }
170
+ };
171
+
172
+ /// \brief Array of Month, Day and nanosecond values.
173
+ class ARROW_EXPORT MonthDayNanoIntervalArray : public PrimitiveArray {
174
+ public:
175
+ using TypeClass = MonthDayNanoIntervalType;
176
+ using IteratorType = stl::ArrayIterator<MonthDayNanoIntervalArray>;
177
+
178
+ explicit MonthDayNanoIntervalArray(const std::shared_ptr<ArrayData>& data);
179
+
180
+ MonthDayNanoIntervalArray(const std::shared_ptr<DataType>& type, int64_t length,
181
+ const std::shared_ptr<Buffer>& data,
182
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
183
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
184
+
185
+ MonthDayNanoIntervalArray(int64_t length, const std::shared_ptr<Buffer>& data,
186
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
187
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
188
+
189
+ TypeClass::MonthDayNanos GetValue(int64_t i) const;
190
+ TypeClass::MonthDayNanos Value(int64_t i) const { return GetValue(i); }
191
+
192
+ // For compatibility with Take kernel.
193
+ TypeClass::MonthDayNanos GetView(int64_t i) const { return GetValue(i); }
194
+
195
+ IteratorType begin() const { return IteratorType(*this); }
196
+
197
+ IteratorType end() const { return IteratorType(*this, length()); }
198
+
199
+ std::optional<TypeClass::MonthDayNanos> operator[](int64_t i) const {
200
+ return *IteratorType(*this, i);
201
+ }
202
+
203
+ int32_t byte_width() const { return sizeof(TypeClass::MonthDayNanos); }
204
+
205
+ const uint8_t* raw_values() const { return raw_values_ + data_->offset * byte_width(); }
206
+ };
207
+
208
+ /// @}
209
+
210
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/c/abi.h ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ /// \file abi.h Arrow C Data Interface
19
+ ///
20
+ /// The Arrow C Data interface defines a very small, stable set
21
+ /// of C definitions which can be easily copied into any project's
22
+ /// source code and vendored to be used for columnar data interchange
23
+ /// in the Arrow format. For non-C/C++ languages and runtimes,
24
+ /// it should be almost as easy to translate the C definitions into
25
+ /// the corresponding C FFI declarations.
26
+ ///
27
+ /// Applications and libraries can therefore work with Arrow memory
28
+ /// without necessarily using the Arrow libraries or reinventing
29
+ /// the wheel. Developers can choose between tight integration
30
+ /// with the Arrow software project or minimal integration with
31
+ /// the Arrow format only.
32
+
33
+ #pragma once
34
+
35
+ #include <stdint.h>
36
+
37
+ // Spec and documentation: https://arrow.apache.org/docs/format/CDataInterface.html
38
+
39
+ #ifdef __cplusplus
40
+ extern "C" {
41
+ #endif
42
+
43
+ #ifndef ARROW_C_DATA_INTERFACE
44
+ # define ARROW_C_DATA_INTERFACE
45
+
46
+ # define ARROW_FLAG_DICTIONARY_ORDERED 1
47
+ # define ARROW_FLAG_NULLABLE 2
48
+ # define ARROW_FLAG_MAP_KEYS_SORTED 4
49
+
50
+ struct ArrowSchema {
51
+ // Array type description
52
+ const char* format;
53
+ const char* name;
54
+ const char* metadata;
55
+ int64_t flags;
56
+ int64_t n_children;
57
+ struct ArrowSchema** children;
58
+ struct ArrowSchema* dictionary;
59
+
60
+ // Release callback
61
+ void (*release)(struct ArrowSchema*);
62
+ // Opaque producer-specific data
63
+ void* private_data;
64
+ };
65
+
66
+ struct ArrowArray {
67
+ // Array data description
68
+ int64_t length;
69
+ int64_t null_count;
70
+ int64_t offset;
71
+ int64_t n_buffers;
72
+ int64_t n_children;
73
+ const void** buffers;
74
+ struct ArrowArray** children;
75
+ struct ArrowArray* dictionary;
76
+
77
+ // Release callback
78
+ void (*release)(struct ArrowArray*);
79
+ // Opaque producer-specific data
80
+ void* private_data;
81
+ };
82
+
83
+ #endif // ARROW_C_DATA_INTERFACE
84
+
85
+ #ifndef ARROW_C_DEVICE_DATA_INTERFACE
86
+ # define ARROW_C_DEVICE_DATA_INTERFACE
87
+
88
+ // Spec and Documentation: https://arrow.apache.org/docs/format/CDeviceDataInterface.html
89
+
90
+ // DeviceType for the allocated memory
91
+ typedef int32_t ArrowDeviceType;
92
+
93
+ // CPU device, same as using ArrowArray directly
94
+ # define ARROW_DEVICE_CPU 1
95
+ // CUDA GPU Device
96
+ # define ARROW_DEVICE_CUDA 2
97
+ // Pinned CUDA CPU memory by cudaMallocHost
98
+ # define ARROW_DEVICE_CUDA_HOST 3
99
+ // OpenCL Device
100
+ # define ARROW_DEVICE_OPENCL 4
101
+ // Vulkan buffer for next-gen graphics
102
+ # define ARROW_DEVICE_VULKAN 7
103
+ // Metal for Apple GPU
104
+ # define ARROW_DEVICE_METAL 8
105
+ // Verilog simulator buffer
106
+ # define ARROW_DEVICE_VPI 9
107
+ // ROCm GPUs for AMD GPUs
108
+ # define ARROW_DEVICE_ROCM 10
109
+ // Pinned ROCm CPU memory allocated by hipMallocHost
110
+ # define ARROW_DEVICE_ROCM_HOST 11
111
+ // Reserved for extension
112
+ # define ARROW_DEVICE_EXT_DEV 12
113
+ // CUDA managed/unified memory allocated by cudaMallocManaged
114
+ # define ARROW_DEVICE_CUDA_MANAGED 13
115
+ // unified shared memory allocated on a oneAPI non-partitioned device.
116
+ # define ARROW_DEVICE_ONEAPI 14
117
+ // GPU support for next-gen WebGPU standard
118
+ # define ARROW_DEVICE_WEBGPU 15
119
+ // Qualcomm Hexagon DSP
120
+ # define ARROW_DEVICE_HEXAGON 16
121
+
122
+ struct ArrowDeviceArray {
123
+ // the Allocated Array
124
+ //
125
+ // the buffers in the array (along with the buffers of any
126
+ // children) are what is allocated on the device.
127
+ struct ArrowArray array;
128
+ // The device id to identify a specific device
129
+ int64_t device_id;
130
+ // The type of device which can access this memory.
131
+ ArrowDeviceType device_type;
132
+ // An event-like object to synchronize on if needed.
133
+ void* sync_event;
134
+ // Reserved bytes for future expansion.
135
+ int64_t reserved[3];
136
+ };
137
+
138
+ #endif // ARROW_C_DEVICE_DATA_INTERFACE
139
+
140
+ #ifndef ARROW_C_STREAM_INTERFACE
141
+ # define ARROW_C_STREAM_INTERFACE
142
+
143
+ struct ArrowArrayStream {
144
+ // Callback to get the stream type
145
+ // (will be the same for all arrays in the stream).
146
+ //
147
+ // Return value: 0 if successful, an `errno`-compatible error code otherwise.
148
+ //
149
+ // If successful, the ArrowSchema must be released independently from the stream.
150
+ int (*get_schema)(struct ArrowArrayStream*, struct ArrowSchema* out);
151
+
152
+ // Callback to get the next array
153
+ // (if no error and the array is released, the stream has ended)
154
+ //
155
+ // Return value: 0 if successful, an `errno`-compatible error code otherwise.
156
+ //
157
+ // If successful, the ArrowArray must be released independently from the stream.
158
+ int (*get_next)(struct ArrowArrayStream*, struct ArrowArray* out);
159
+
160
+ // Callback to get optional detailed error information.
161
+ // This must only be called if the last stream operation failed
162
+ // with a non-0 return code.
163
+ //
164
+ // Return value: pointer to a null-terminated character array describing
165
+ // the last error, or NULL if no description is available.
166
+ //
167
+ // The returned pointer is only valid until the next operation on this stream
168
+ // (including release).
169
+ const char* (*get_last_error)(struct ArrowArrayStream*);
170
+
171
+ // Release callback: release the stream's own resources.
172
+ // Note that arrays returned by `get_next` must be individually released.
173
+ void (*release)(struct ArrowArrayStream*);
174
+
175
+ // Opaque producer-specific data
176
+ void* private_data;
177
+ };
178
+
179
+ #endif // ARROW_C_STREAM_INTERFACE
180
+
181
+ #ifndef ARROW_C_DEVICE_STREAM_INTERFACE
182
+ # define ARROW_C_DEVICE_STREAM_INTERFACE
183
+
184
+ // Equivalent to ArrowArrayStream, but for ArrowDeviceArrays.
185
+ //
186
+ // This stream is intended to provide a stream of data on a single
187
+ // device, if a producer wants data to be produced on multiple devices
188
+ // then multiple streams should be provided. One per device.
189
+ struct ArrowDeviceArrayStream {
190
+ // The device that this stream produces data on.
191
+ ArrowDeviceType device_type;
192
+
193
+ // Callback to get the stream schema
194
+ // (will be the same for all arrays in the stream).
195
+ //
196
+ // Return value 0 if successful, an `errno`-compatible error code otherwise.
197
+ //
198
+ // If successful, the ArrowSchema must be released independently from the stream.
199
+ // The schema should be accessible via CPU memory.
200
+ int (*get_schema)(struct ArrowDeviceArrayStream* self, struct ArrowSchema* out);
201
+
202
+ // Callback to get the next array
203
+ // (if no error and the array is released, the stream has ended)
204
+ //
205
+ // Return value: 0 if successful, an `errno`-compatible error code otherwise.
206
+ //
207
+ // If successful, the ArrowDeviceArray must be released independently from the stream.
208
+ int (*get_next)(struct ArrowDeviceArrayStream* self, struct ArrowDeviceArray* out);
209
+
210
+ // Callback to get optional detailed error information.
211
+ // This must only be called if the last stream operation failed
212
+ // with a non-0 return code.
213
+ //
214
+ // Return value: pointer to a null-terminated character array describing
215
+ // the last error, or NULL if no description is available.
216
+ //
217
+ // The returned pointer is only valid until the next operation on this stream
218
+ // (including release).
219
+ const char* (*get_last_error)(struct ArrowDeviceArrayStream* self);
220
+
221
+ // Release callback: release the stream's own resources.
222
+ // Note that arrays returned by `get_next` must be individually released.
223
+ void (*release)(struct ArrowDeviceArrayStream* self);
224
+
225
+ // Opaque producer-specific data
226
+ void* private_data;
227
+ };
228
+
229
+ #endif // ARROW_C_DEVICE_STREAM_INTERFACE
230
+
231
+ #ifdef __cplusplus
232
+ }
233
+ #endif
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/c/bridge.h ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <functional>
21
+ #include <memory>
22
+ #include <string>
23
+
24
+ #include "arrow/c/abi.h"
25
+ #include "arrow/device.h"
26
+ #include "arrow/result.h"
27
+ #include "arrow/status.h"
28
+ #include "arrow/type_fwd.h"
29
+ #include "arrow/util/macros.h"
30
+ #include "arrow/util/visibility.h"
31
+
32
+ namespace arrow {
33
+
34
+ /// \defgroup c-data-interface Functions for working with the C data interface.
35
+ ///
36
+ /// @{
37
+
38
+ /// \brief Export C++ DataType using the C data interface format.
39
+ ///
40
+ /// The root type is considered to have empty name and metadata.
41
+ /// If you want the root type to have a name and/or metadata, pass
42
+ /// a Field instead.
43
+ ///
44
+ /// \param[in] type DataType object to export
45
+ /// \param[out] out C struct where to export the datatype
46
+ ARROW_EXPORT
47
+ Status ExportType(const DataType& type, struct ArrowSchema* out);
48
+
49
+ /// \brief Export C++ Field using the C data interface format.
50
+ ///
51
+ /// \param[in] field Field object to export
52
+ /// \param[out] out C struct where to export the field
53
+ ARROW_EXPORT
54
+ Status ExportField(const Field& field, struct ArrowSchema* out);
55
+
56
+ /// \brief Export C++ Schema using the C data interface format.
57
+ ///
58
+ /// \param[in] schema Schema object to export
59
+ /// \param[out] out C struct where to export the field
60
+ ARROW_EXPORT
61
+ Status ExportSchema(const Schema& schema, struct ArrowSchema* out);
62
+
63
+ /// \brief Export C++ Array using the C data interface format.
64
+ ///
65
+ /// The resulting ArrowArray struct keeps the array data and buffers alive
66
+ /// until its release callback is called by the consumer.
67
+ ///
68
+ /// \param[in] array Array object to export
69
+ /// \param[out] out C struct where to export the array
70
+ /// \param[out] out_schema optional C struct where to export the array type
71
+ ARROW_EXPORT
72
+ Status ExportArray(const Array& array, struct ArrowArray* out,
73
+ struct ArrowSchema* out_schema = NULLPTR);
74
+
75
+ /// \brief Export C++ RecordBatch using the C data interface format.
76
+ ///
77
+ /// The record batch is exported as if it were a struct array.
78
+ /// The resulting ArrowArray struct keeps the record batch data and buffers alive
79
+ /// until its release callback is called by the consumer.
80
+ ///
81
+ /// \param[in] batch Record batch to export
82
+ /// \param[out] out C struct where to export the record batch
83
+ /// \param[out] out_schema optional C struct where to export the record batch schema
84
+ ARROW_EXPORT
85
+ Status ExportRecordBatch(const RecordBatch& batch, struct ArrowArray* out,
86
+ struct ArrowSchema* out_schema = NULLPTR);
87
+
88
+ /// \brief Import C++ DataType from the C data interface.
89
+ ///
90
+ /// The given ArrowSchema struct is released (as per the C data interface
91
+ /// specification), even if this function fails.
92
+ ///
93
+ /// \param[in,out] schema C data interface struct representing the data type
94
+ /// \return Imported type object
95
+ ARROW_EXPORT
96
+ Result<std::shared_ptr<DataType>> ImportType(struct ArrowSchema* schema);
97
+
98
+ /// \brief Import C++ Field from the C data interface.
99
+ ///
100
+ /// The given ArrowSchema struct is released (as per the C data interface
101
+ /// specification), even if this function fails.
102
+ ///
103
+ /// \param[in,out] schema C data interface struct representing the field
104
+ /// \return Imported field object
105
+ ARROW_EXPORT
106
+ Result<std::shared_ptr<Field>> ImportField(struct ArrowSchema* schema);
107
+
108
+ /// \brief Import C++ Schema from the C data interface.
109
+ ///
110
+ /// The given ArrowSchema struct is released (as per the C data interface
111
+ /// specification), even if this function fails.
112
+ ///
113
+ /// \param[in,out] schema C data interface struct representing the field
114
+ /// \return Imported field object
115
+ ARROW_EXPORT
116
+ Result<std::shared_ptr<Schema>> ImportSchema(struct ArrowSchema* schema);
117
+
118
+ /// \brief Import C++ array from the C data interface.
119
+ ///
120
+ /// The ArrowArray struct has its contents moved (as per the C data interface
121
+ /// specification) to a private object held alive by the resulting array.
122
+ ///
123
+ /// \param[in,out] array C data interface struct holding the array data
124
+ /// \param[in] type type of the imported array
125
+ /// \return Imported array object
126
+ ARROW_EXPORT
127
+ Result<std::shared_ptr<Array>> ImportArray(struct ArrowArray* array,
128
+ std::shared_ptr<DataType> type);
129
+
130
+ /// \brief Import C++ array and its type from the C data interface.
131
+ ///
132
+ /// The ArrowArray struct has its contents moved (as per the C data interface
133
+ /// specification) to a private object held alive by the resulting array.
134
+ /// The ArrowSchema struct is released, even if this function fails.
135
+ ///
136
+ /// \param[in,out] array C data interface struct holding the array data
137
+ /// \param[in,out] type C data interface struct holding the array type
138
+ /// \return Imported array object
139
+ ARROW_EXPORT
140
+ Result<std::shared_ptr<Array>> ImportArray(struct ArrowArray* array,
141
+ struct ArrowSchema* type);
142
+
143
+ /// \brief Import C++ record batch from the C data interface.
144
+ ///
145
+ /// The ArrowArray struct has its contents moved (as per the C data interface
146
+ /// specification) to a private object held alive by the resulting record batch.
147
+ ///
148
+ /// \param[in,out] array C data interface struct holding the record batch data
149
+ /// \param[in] schema schema of the imported record batch
150
+ /// \return Imported record batch object
151
+ ARROW_EXPORT
152
+ Result<std::shared_ptr<RecordBatch>> ImportRecordBatch(struct ArrowArray* array,
153
+ std::shared_ptr<Schema> schema);
154
+
155
+ /// \brief Import C++ record batch and its schema from the C data interface.
156
+ ///
157
+ /// The type represented by the ArrowSchema struct must be a struct type array.
158
+ /// The ArrowArray struct has its contents moved (as per the C data interface
159
+ /// specification) to a private object held alive by the resulting record batch.
160
+ /// The ArrowSchema struct is released, even if this function fails.
161
+ ///
162
+ /// \param[in,out] array C data interface struct holding the record batch data
163
+ /// \param[in,out] schema C data interface struct holding the record batch schema
164
+ /// \return Imported record batch object
165
+ ARROW_EXPORT
166
+ Result<std::shared_ptr<RecordBatch>> ImportRecordBatch(struct ArrowArray* array,
167
+ struct ArrowSchema* schema);
168
+
169
+ /// @}
170
+
171
+ /// \defgroup c-data-device-interface Functions for working with the C data device
172
+ /// interface.
173
+ ///
174
+ /// @{
175
+
176
+ /// \brief EXPERIMENTAL: Export C++ Array as an ArrowDeviceArray.
177
+ ///
178
+ /// The resulting ArrowDeviceArray struct keeps the array data and buffers alive
179
+ /// until its release callback is called by the consumer. All buffers in
180
+ /// the provided array MUST have the same device_type, otherwise an error
181
+ /// will be returned.
182
+ ///
183
+ /// If sync is non-null, get_event will be called on it in order to
184
+ /// potentially provide an event for consumers to synchronize on.
185
+ ///
186
+ /// \param[in] array Array object to export
187
+ /// \param[in] sync shared_ptr to object derived from Device::SyncEvent or null
188
+ /// \param[out] out C struct to export the array to
189
+ /// \param[out] out_schema optional C struct to export the array type to
190
+ ARROW_EXPORT
191
+ Status ExportDeviceArray(const Array& array, std::shared_ptr<Device::SyncEvent> sync,
192
+ struct ArrowDeviceArray* out,
193
+ struct ArrowSchema* out_schema = NULLPTR);
194
+
195
+ /// \brief EXPERIMENTAL: Export C++ RecordBatch as an ArrowDeviceArray.
196
+ ///
197
+ /// The record batch is exported as if it were a struct array.
198
+ /// The resulting ArrowDeviceArray struct keeps the record batch data and buffers alive
199
+ /// until its release callback is called by the consumer.
200
+ ///
201
+ /// All buffers of all columns in the record batch must have the same device_type
202
+ /// otherwise an error will be returned. If columns are on different devices,
203
+ /// they should be exported using different ArrowDeviceArray instances.
204
+ ///
205
+ /// If sync is non-null, get_event will be called on it in order to
206
+ /// potentially provide an event for consumers to synchronize on.
207
+ ///
208
+ /// \param[in] batch Record batch to export
209
+ /// \param[in] sync shared_ptr to object derived from Device::SyncEvent or null
210
+ /// \param[out] out C struct where to export the record batch
211
+ /// \param[out] out_schema optional C struct where to export the record batch schema
212
+ ARROW_EXPORT
213
+ Status ExportDeviceRecordBatch(const RecordBatch& batch,
214
+ std::shared_ptr<Device::SyncEvent> sync,
215
+ struct ArrowDeviceArray* out,
216
+ struct ArrowSchema* out_schema = NULLPTR);
217
+
218
+ using DeviceMemoryMapper =
219
+ std::function<Result<std::shared_ptr<MemoryManager>>(ArrowDeviceType, int64_t)>;
220
+
221
+ ARROW_EXPORT
222
+ Result<std::shared_ptr<MemoryManager>> DefaultDeviceMemoryMapper(
223
+ ArrowDeviceType device_type, int64_t device_id);
224
+
225
+ /// \brief EXPERIMENTAL: Import C++ device array from the C data interface.
226
+ ///
227
+ /// The ArrowArray struct has its contents moved (as per the C data interface
228
+ /// specification) to a private object held alive by the resulting array. The
229
+ /// buffers of the Array are located on the device indicated by the device_type.
230
+ ///
231
+ /// \param[in,out] array C data interface struct holding the array data
232
+ /// \param[in] type type of the imported array
233
+ /// \param[in] mapper A function to map device + id to memory manager. If not
234
+ /// specified, defaults to map "cpu" to the built-in default memory manager.
235
+ /// \return Imported array object
236
+ ARROW_EXPORT
237
+ Result<std::shared_ptr<Array>> ImportDeviceArray(
238
+ struct ArrowDeviceArray* array, std::shared_ptr<DataType> type,
239
+ const DeviceMemoryMapper& mapper = DefaultDeviceMemoryMapper);
240
+
241
+ /// \brief EXPERIMENTAL: Import C++ device array and its type from the C data interface.
242
+ ///
243
+ /// The ArrowArray struct has its contents moved (as per the C data interface
244
+ /// specification) to a private object held alive by the resulting array.
245
+ /// The ArrowSchema struct is released, even if this function fails. The
246
+ /// buffers of the Array are located on the device indicated by the device_type.
247
+ ///
248
+ /// \param[in,out] array C data interface struct holding the array data
249
+ /// \param[in,out] type C data interface struct holding the array type
250
+ /// \param[in] mapper A function to map device + id to memory manager. If not
251
+ /// specified, defaults to map "cpu" to the built-in default memory manager.
252
+ /// \return Imported array object
253
+ ARROW_EXPORT
254
+ Result<std::shared_ptr<Array>> ImportDeviceArray(
255
+ struct ArrowDeviceArray* array, struct ArrowSchema* type,
256
+ const DeviceMemoryMapper& mapper = DefaultDeviceMemoryMapper);
257
+
258
+ /// \brief EXPERIMENTAL: Import C++ record batch with buffers on a device from the C data
259
+ /// interface.
260
+ ///
261
+ /// The ArrowArray struct has its contents moved (as per the C data interface
262
+ /// specification) to a private object held alive by the resulting record batch.
263
+ /// The buffers of all columns of the record batch are located on the device
264
+ /// indicated by the device type.
265
+ ///
266
+ /// \param[in,out] array C data interface struct holding the record batch data
267
+ /// \param[in] schema schema of the imported record batch
268
+ /// \param[in] mapper A function to map device + id to memory manager. If not
269
+ /// specified, defaults to map "cpu" to the built-in default memory manager.
270
+ /// \return Imported record batch object
271
+ ARROW_EXPORT
272
+ Result<std::shared_ptr<RecordBatch>> ImportDeviceRecordBatch(
273
+ struct ArrowDeviceArray* array, std::shared_ptr<Schema> schema,
274
+ const DeviceMemoryMapper& mapper = DefaultDeviceMemoryMapper);
275
+
276
+ /// \brief EXPERIMENTAL: Import C++ record batch with buffers on a device and its schema
277
+ /// from the C data interface.
278
+ ///
279
+ /// The type represented by the ArrowSchema struct must be a struct type array.
280
+ /// The ArrowArray struct has its contents moved (as per the C data interface
281
+ /// specification) to a private object held alive by the resulting record batch.
282
+ /// The ArrowSchema struct is released, even if this function fails. The buffers
283
+ /// of all columns of the record batch are located on the device indicated by the
284
+ /// device type.
285
+ ///
286
+ /// \param[in,out] array C data interface struct holding the record batch data
287
+ /// \param[in,out] schema C data interface struct holding the record batch schema
288
+ /// \param[in] mapper A function to map device + id to memory manager. If not
289
+ /// specified, defaults to map "cpu" to the built-in default memory manager.
290
+ /// \return Imported record batch object
291
+ ARROW_EXPORT
292
+ Result<std::shared_ptr<RecordBatch>> ImportDeviceRecordBatch(
293
+ struct ArrowDeviceArray* array, struct ArrowSchema* schema,
294
+ const DeviceMemoryMapper& mapper = DefaultDeviceMemoryMapper);
295
+
296
+ /// @}
297
+
298
+ /// \defgroup c-stream-interface Functions for working with the C data interface.
299
+ ///
300
+ /// @{
301
+
302
+ /// \brief Export C++ RecordBatchReader using the C stream interface.
303
+ ///
304
+ /// The resulting ArrowArrayStream struct keeps the record batch reader alive
305
+ /// until its release callback is called by the consumer.
306
+ ///
307
+ /// \param[in] reader RecordBatchReader object to export
308
+ /// \param[out] out C struct where to export the stream
309
+ ARROW_EXPORT
310
+ Status ExportRecordBatchReader(std::shared_ptr<RecordBatchReader> reader,
311
+ struct ArrowArrayStream* out);
312
+
313
+ /// \brief Export C++ ChunkedArray using the C data interface format.
314
+ ///
315
+ /// The resulting ArrowArrayStream struct keeps the chunked array data and buffers alive
316
+ /// until its release callback is called by the consumer.
317
+ ///
318
+ /// \param[in] chunked_array ChunkedArray object to export
319
+ /// \param[out] out C struct where to export the stream
320
+ ARROW_EXPORT
321
+ Status ExportChunkedArray(std::shared_ptr<ChunkedArray> chunked_array,
322
+ struct ArrowArrayStream* out);
323
+
324
+ /// \brief Export C++ RecordBatchReader using the C device stream interface
325
+ ///
326
+ /// The resulting ArrowDeviceArrayStream struct keeps the record batch reader
327
+ /// alive until its release callback is called by the consumer. The device
328
+ /// type is determined by calling device_type() on the RecordBatchReader.
329
+ ///
330
+ /// \param[in] reader RecordBatchReader object to export
331
+ /// \param[out] out C struct to export the stream to
332
+ ARROW_EXPORT
333
+ Status ExportDeviceRecordBatchReader(std::shared_ptr<RecordBatchReader> reader,
334
+ struct ArrowDeviceArrayStream* out);
335
+
336
+ /// \brief Export C++ ChunkedArray using the C device data interface format.
337
+ ///
338
+ /// The resulting ArrowDeviceArrayStream keeps the chunked array data and buffers
339
+ /// alive until its release callback is called by the consumer.
340
+ ///
341
+ /// \param[in] chunked_array ChunkedArray object to export
342
+ /// \param[in] device_type the device type the data is located on
343
+ /// \param[out] out C struct to export the stream to
344
+ ARROW_EXPORT
345
+ Status ExportDeviceChunkedArray(std::shared_ptr<ChunkedArray> chunked_array,
346
+ DeviceAllocationType device_type,
347
+ struct ArrowDeviceArrayStream* out);
348
+
349
+ /// \brief Import C++ RecordBatchReader from the C stream interface.
350
+ ///
351
+ /// The ArrowArrayStream struct has its contents moved to a private object
352
+ /// held alive by the resulting record batch reader.
353
+ ///
354
+ /// \param[in,out] stream C stream interface struct
355
+ /// \return Imported RecordBatchReader object
356
+ ARROW_EXPORT
357
+ Result<std::shared_ptr<RecordBatchReader>> ImportRecordBatchReader(
358
+ struct ArrowArrayStream* stream);
359
+
360
+ /// \brief Import C++ ChunkedArray from the C stream interface
361
+ ///
362
+ /// The ArrowArrayStream struct has its contents moved to a private object,
363
+ /// is consumed in its entirity, and released before returning all chunks
364
+ /// as a ChunkedArray.
365
+ ///
366
+ /// \param[in,out] stream C stream interface struct
367
+ /// \return Imported ChunkedArray object
368
+ ARROW_EXPORT
369
+ Result<std::shared_ptr<ChunkedArray>> ImportChunkedArray(struct ArrowArrayStream* stream);
370
+
371
+ /// \brief Import C++ RecordBatchReader from the C device stream interface
372
+ ///
373
+ /// The ArrowDeviceArrayStream struct has its contents moved to a private object
374
+ /// held alive by the resulting record batch reader.
375
+ ///
376
+ /// \note If there was a required sync event, sync events are accessible by individual
377
+ /// buffers of columns. We are not yet bubbling the sync events from the buffers up to
378
+ /// the `GetSyncEvent` method of an imported RecordBatch. This will be added in a future
379
+ /// update.
380
+ ///
381
+ /// \param[in,out] stream C device stream interface struct
382
+ /// \param[in] mapper mapping from device type and ID to memory manager
383
+ /// \return Imported RecordBatchReader object
384
+ ARROW_EXPORT
385
+ Result<std::shared_ptr<RecordBatchReader>> ImportDeviceRecordBatchReader(
386
+ struct ArrowDeviceArrayStream* stream,
387
+ const DeviceMemoryMapper& mapper = DefaultDeviceMemoryMapper);
388
+
389
+ /// \brief Import C++ ChunkedArray from the C device stream interface
390
+ ///
391
+ /// The ArrowDeviceArrayStream struct has its contents moved to a private object,
392
+ /// is consumed in its entirety, and released before returning all chunks as a
393
+ /// ChunkedArray.
394
+ ///
395
+ /// \note Any chunks that require synchronization for their device memory will have
396
+ /// the SyncEvent objects available by checking the individual buffers of each chunk.
397
+ /// These SyncEvents should be checked before accessing the data in those buffers.
398
+ ///
399
+ /// \param[in,out] stream C device stream interface struct
400
+ /// \param[in] mapper mapping from device type and ID to memory manager
401
+ /// \return Imported ChunkedArray object
402
+ ARROW_EXPORT
403
+ Result<std::shared_ptr<ChunkedArray>> ImportDeviceChunkedArray(
404
+ struct ArrowDeviceArrayStream* stream,
405
+ const DeviceMemoryMapper& mapper = DefaultDeviceMemoryMapper);
406
+
407
+ /// @}
408
+
409
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/c/dlpack_abi.h ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Taken from:
2
+ // https://github.com/dmlc/dlpack/blob/ca4d00ad3e2e0f410eeab3264d21b8a39397f362/include/dlpack/dlpack.h
3
+ /*!
4
+ * Copyright (c) 2017 by Contributors
5
+ * \file dlpack.h
6
+ * \brief The common header of DLPack.
7
+ */
8
+ #ifndef DLPACK_DLPACK_H_
9
+ #define DLPACK_DLPACK_H_
10
+
11
+ /**
12
+ * \brief Compatibility with C++
13
+ */
14
+ #ifdef __cplusplus
15
+ # define DLPACK_EXTERN_C extern "C"
16
+ #else
17
+ # define DLPACK_EXTERN_C
18
+ #endif
19
+
20
+ /*! \brief The current major version of dlpack */
21
+ #define DLPACK_MAJOR_VERSION 1
22
+
23
+ /*! \brief The current minor version of dlpack */
24
+ #define DLPACK_MINOR_VERSION 0
25
+
26
+ /*! \brief DLPACK_DLL prefix for windows */
27
+ #ifdef _WIN32
28
+ # ifdef DLPACK_EXPORTS
29
+ # define DLPACK_DLL __declspec(dllexport)
30
+ # else
31
+ # define DLPACK_DLL __declspec(dllimport)
32
+ # endif
33
+ #else
34
+ # define DLPACK_DLL
35
+ #endif
36
+
37
+ #include <stddef.h>
38
+ #include <stdint.h>
39
+
40
+ #ifdef __cplusplus
41
+ extern "C" {
42
+ #endif
43
+
44
+ /*!
45
+ * \brief The DLPack version.
46
+ *
47
+ * A change in major version indicates that we have changed the
48
+ * data layout of the ABI - DLManagedTensorVersioned.
49
+ *
50
+ * A change in minor version indicates that we have added new
51
+ * code, such as a new device type, but the ABI is kept the same.
52
+ *
53
+ * If an obtained DLPack tensor has a major version that disagrees
54
+ * with the version number specified in this header file
55
+ * (i.e. major != DLPACK_MAJOR_VERSION), the consumer must call the deleter
56
+ * (and it is safe to do so). It is not safe to access any other fields
57
+ * as the memory layout will have changed.
58
+ *
59
+ * In the case of a minor version mismatch, the tensor can be safely used as
60
+ * long as the consumer knows how to interpret all fields. Minor version
61
+ * updates indicate the addition of enumeration values.
62
+ */
63
+ typedef struct {
64
+ /*! \brief DLPack major version. */
65
+ uint32_t major;
66
+ /*! \brief DLPack minor version. */
67
+ uint32_t minor;
68
+ } DLPackVersion;
69
+
70
+ /*!
71
+ * \brief The device type in DLDevice.
72
+ */
73
+ #ifdef __cplusplus
74
+ typedef enum : int32_t {
75
+ #else
76
+ typedef enum {
77
+ #endif
78
+ /*! \brief CPU device */
79
+ kDLCPU = 1,
80
+ /*! \brief CUDA GPU device */
81
+ kDLCUDA = 2,
82
+ /*!
83
+ * \brief Pinned CUDA CPU memory by cudaMallocHost
84
+ */
85
+ kDLCUDAHost = 3,
86
+ /*! \brief OpenCL devices. */
87
+ kDLOpenCL = 4,
88
+ /*! \brief Vulkan buffer for next generation graphics. */
89
+ kDLVulkan = 7,
90
+ /*! \brief Metal for Apple GPU. */
91
+ kDLMetal = 8,
92
+ /*! \brief Verilog simulator buffer */
93
+ kDLVPI = 9,
94
+ /*! \brief ROCm GPUs for AMD GPUs */
95
+ kDLROCM = 10,
96
+ /*!
97
+ * \brief Pinned ROCm CPU memory allocated by hipMallocHost
98
+ */
99
+ kDLROCMHost = 11,
100
+ /*!
101
+ * \brief Reserved extension device type,
102
+ * used for quickly test extension device
103
+ * The semantics can differ depending on the implementation.
104
+ */
105
+ kDLExtDev = 12,
106
+ /*!
107
+ * \brief CUDA managed/unified memory allocated by cudaMallocManaged
108
+ */
109
+ kDLCUDAManaged = 13,
110
+ /*!
111
+ * \brief Unified shared memory allocated on a oneAPI non-partititioned
112
+ * device. Call to oneAPI runtime is required to determine the device
113
+ * type, the USM allocation type and the sycl context it is bound to.
114
+ *
115
+ */
116
+ kDLOneAPI = 14,
117
+ /*! \brief GPU support for next generation WebGPU standard. */
118
+ kDLWebGPU = 15,
119
+ /*! \brief Qualcomm Hexagon DSP */
120
+ kDLHexagon = 16,
121
+ } DLDeviceType;
122
+
123
+ /*!
124
+ * \brief A Device for Tensor and operator.
125
+ */
126
+ typedef struct {
127
+ /*! \brief The device type used in the device. */
128
+ DLDeviceType device_type;
129
+ /*!
130
+ * \brief The device index.
131
+ * For vanilla CPU memory, pinned memory, or managed memory, this is set to 0.
132
+ */
133
+ int32_t device_id;
134
+ } DLDevice;
135
+
136
+ /*!
137
+ * \brief The type code options DLDataType.
138
+ */
139
+ typedef enum {
140
+ /*! \brief signed integer */
141
+ kDLInt = 0U,
142
+ /*! \brief unsigned integer */
143
+ kDLUInt = 1U,
144
+ /*! \brief IEEE floating point */
145
+ kDLFloat = 2U,
146
+ /*!
147
+ * \brief Opaque handle type, reserved for testing purposes.
148
+ * Frameworks need to agree on the handle data type for the exchange to be well-defined.
149
+ */
150
+ kDLOpaqueHandle = 3U,
151
+ /*! \brief bfloat16 */
152
+ kDLBfloat = 4U,
153
+ /*!
154
+ * \brief complex number
155
+ * (C/C++/Python layout: compact struct per complex number)
156
+ */
157
+ kDLComplex = 5U,
158
+ /*! \brief boolean */
159
+ kDLBool = 6U,
160
+ } DLDataTypeCode;
161
+
162
+ /*!
163
+ * \brief The data type the tensor can hold. The data type is assumed to follow the
164
+ * native endian-ness. An explicit error message should be raised when attempting to
165
+ * export an array with non-native endianness
166
+ *
167
+ * Examples
168
+ * - float: type_code = 2, bits = 32, lanes = 1
169
+ * - float4(vectorized 4 float): type_code = 2, bits = 32, lanes = 4
170
+ * - int8: type_code = 0, bits = 8, lanes = 1
171
+ * - std::complex<float>: type_code = 5, bits = 64, lanes = 1
172
+ * - bool: type_code = 6, bits = 8, lanes = 1 (as per common array library convention,
173
+ * the underlying storage size of bool is 8 bits)
174
+ */
175
+ typedef struct {
176
+ /*!
177
+ * \brief Type code of base types.
178
+ * We keep it uint8_t instead of DLDataTypeCode for minimal memory
179
+ * footprint, but the value should be one of DLDataTypeCode enum values.
180
+ * */
181
+ uint8_t code;
182
+ /*!
183
+ * \brief Number of bits, common choices are 8, 16, 32.
184
+ */
185
+ uint8_t bits;
186
+ /*! \brief Number of lanes in the type, used for vector types. */
187
+ uint16_t lanes;
188
+ } DLDataType;
189
+
190
+ /*!
191
+ * \brief Plain C Tensor object, does not manage memory.
192
+ */
193
+ typedef struct {
194
+ /*!
195
+ * \brief The data pointer points to the allocated data. This will be CUDA
196
+ * device pointer or cl_mem handle in OpenCL. It may be opaque on some device
197
+ * types. This pointer is always aligned to 256 bytes as in CUDA. The
198
+ * `byte_offset` field should be used to point to the beginning of the data.
199
+ *
200
+ * Note that as of Nov 2021, multiply libraries (CuPy, PyTorch, TensorFlow,
201
+ * TVM, perhaps others) do not adhere to this 256 byte aligment requirement
202
+ * on CPU/CUDA/ROCm, and always use `byte_offset=0`. This must be fixed
203
+ * (after which this note will be updated); at the moment it is recommended
204
+ * to not rely on the data pointer being correctly aligned.
205
+ *
206
+ * For given DLTensor, the size of memory required to store the contents of
207
+ * data is calculated as follows:
208
+ *
209
+ * \code{.c}
210
+ * static inline size_t GetDataSize(const DLTensor* t) {
211
+ * size_t size = 1;
212
+ * for (tvm_index_t i = 0; i < t->ndim; ++i) {
213
+ * size *= t->shape[i];
214
+ * }
215
+ * size *= (t->dtype.bits * t->dtype.lanes + 7) / 8;
216
+ * return size;
217
+ * }
218
+ * \endcode
219
+ */
220
+ void* data;
221
+ /*! \brief The device of the tensor */
222
+ DLDevice device;
223
+ /*! \brief Number of dimensions */
224
+ int32_t ndim;
225
+ /*! \brief The data type of the pointer*/
226
+ DLDataType dtype;
227
+ /*! \brief The shape of the tensor */
228
+ int64_t* shape;
229
+ /*!
230
+ * \brief strides of the tensor (in number of elements, not bytes)
231
+ * can be NULL, indicating tensor is compact and row-majored.
232
+ */
233
+ int64_t* strides;
234
+ /*! \brief The offset in bytes to the beginning pointer to data */
235
+ uint64_t byte_offset;
236
+ } DLTensor;
237
+
238
+ /*!
239
+ * \brief C Tensor object, manage memory of DLTensor. This data structure is
240
+ * intended to facilitate the borrowing of DLTensor by another framework. It is
241
+ * not meant to transfer the tensor. When the borrowing framework doesn't need
242
+ * the tensor, it should call the deleter to notify the host that the resource
243
+ * is no longer needed.
244
+ *
245
+ * \note This data structure is used as Legacy DLManagedTensor
246
+ * in DLPack exchange and is deprecated after DLPack v0.8
247
+ * Use DLManagedTensorVersioned instead.
248
+ * This data structure may get renamed or deleted in future versions.
249
+ *
250
+ * \sa DLManagedTensorVersioned
251
+ */
252
+ typedef struct DLManagedTensor {
253
+ /*! \brief DLTensor which is being memory managed */
254
+ DLTensor dl_tensor;
255
+ /*! \brief the context of the original host framework of DLManagedTensor in
256
+ * which DLManagedTensor is used in the framework. It can also be NULL.
257
+ */
258
+ void* manager_ctx;
259
+ /*!
260
+ * \brief Destructor - this should be called
261
+ * to destruct the manager_ctx which backs the DLManagedTensor. It can be
262
+ * NULL if there is no way for the caller to provide a reasonable destructor.
263
+ * The destructors deletes the argument self as well.
264
+ */
265
+ void (*deleter)(struct DLManagedTensor* self);
266
+ } DLManagedTensor;
267
+
268
+ // bit masks used in in the DLManagedTensorVersioned
269
+
270
+ /*! \brief bit mask to indicate that the tensor is read only. */
271
+ #define DLPACK_FLAG_BITMASK_READ_ONLY (1UL << 0UL)
272
+
273
+ /*!
274
+ * \brief A versioned and managed C Tensor object, manage memory of DLTensor.
275
+ *
276
+ * This data structure is intended to facilitate the borrowing of DLTensor by
277
+ * another framework. It is not meant to transfer the tensor. When the borrowing
278
+ * framework doesn't need the tensor, it should call the deleter to notify the
279
+ * host that the resource is no longer needed.
280
+ *
281
+ * \note This is the current standard DLPack exchange data structure.
282
+ */
283
+ struct DLManagedTensorVersioned {
284
+ /*!
285
+ * \brief The API and ABI version of the current managed Tensor
286
+ */
287
+ DLPackVersion version;
288
+ /*!
289
+ * \brief the context of the original host framework.
290
+ *
291
+ * Stores DLManagedTensorVersioned is used in the
292
+ * framework. It can also be NULL.
293
+ */
294
+ void* manager_ctx;
295
+ /*!
296
+ * \brief Destructor.
297
+ *
298
+ * This should be called to destruct manager_ctx which holds the
299
+ * DLManagedTensorVersioned. It can be NULL if there is no way for the caller to provide
300
+ * a reasonable destructor. The destructors deletes the argument self as well.
301
+ */
302
+ void (*deleter)(struct DLManagedTensorVersioned* self);
303
+ /*!
304
+ * \brief Additional bitmask flags information about the tensor.
305
+ *
306
+ * By default the flags should be set to 0.
307
+ *
308
+ * \note Future ABI changes should keep everything until this field
309
+ * stable, to ensure that deleter can be correctly called.
310
+ *
311
+ * \sa DLPACK_FLAG_BITMASK_READ_ONLY
312
+ */
313
+ uint64_t flags;
314
+ /*! \brief DLTensor which is being memory managed */
315
+ DLTensor dl_tensor;
316
+ };
317
+
318
+ #ifdef __cplusplus
319
+ } // DLPACK_EXTERN_C
320
+ #endif
321
+ #endif // DLPACK_DLPACK_H_
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/c/helpers.h ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <assert.h>
21
+ #include <stdio.h>
22
+ #include <stdlib.h>
23
+ #include <string.h>
24
+
25
+ #include "arrow/c/abi.h"
26
+
27
+ #define ARROW_C_ASSERT(condition, msg) \
28
+ do { \
29
+ if (!(condition)) { \
30
+ fprintf(stderr, "%s:%d:: %s", __FILE__, __LINE__, (msg)); \
31
+ abort(); \
32
+ } \
33
+ } while (0)
34
+
35
+ #ifdef __cplusplus
36
+ extern "C" {
37
+ #endif
38
+
39
+ /// Query whether the C schema is released
40
+ inline int ArrowSchemaIsReleased(const struct ArrowSchema* schema) {
41
+ return schema->release == NULL;
42
+ }
43
+
44
+ /// Mark the C schema released (for use in release callbacks)
45
+ inline void ArrowSchemaMarkReleased(struct ArrowSchema* schema) {
46
+ schema->release = NULL;
47
+ }
48
+
49
+ /// Move the C schema from `src` to `dest`
50
+ ///
51
+ /// Note `dest` must *not* point to a valid schema already, otherwise there
52
+ /// will be a memory leak.
53
+ inline void ArrowSchemaMove(struct ArrowSchema* src, struct ArrowSchema* dest) {
54
+ assert(dest != src);
55
+ assert(!ArrowSchemaIsReleased(src));
56
+ memcpy(dest, src, sizeof(struct ArrowSchema));
57
+ ArrowSchemaMarkReleased(src);
58
+ }
59
+
60
+ /// Release the C schema, if necessary, by calling its release callback
61
+ inline void ArrowSchemaRelease(struct ArrowSchema* schema) {
62
+ if (!ArrowSchemaIsReleased(schema)) {
63
+ schema->release(schema);
64
+ ARROW_C_ASSERT(ArrowSchemaIsReleased(schema),
65
+ "ArrowSchemaRelease did not cleanup release callback");
66
+ }
67
+ }
68
+
69
+ /// Query whether the C array is released
70
+ inline int ArrowArrayIsReleased(const struct ArrowArray* array) {
71
+ return array->release == NULL;
72
+ }
73
+
74
+ inline int ArrowDeviceArrayIsReleased(const struct ArrowDeviceArray* array) {
75
+ return ArrowArrayIsReleased(&array->array);
76
+ }
77
+
78
+ /// Mark the C array released (for use in release callbacks)
79
+ inline void ArrowArrayMarkReleased(struct ArrowArray* array) { array->release = NULL; }
80
+
81
+ inline void ArrowDeviceArrayMarkReleased(struct ArrowDeviceArray* array) {
82
+ ArrowArrayMarkReleased(&array->array);
83
+ }
84
+
85
+ /// Move the C array from `src` to `dest`
86
+ ///
87
+ /// Note `dest` must *not* point to a valid array already, otherwise there
88
+ /// will be a memory leak.
89
+ inline void ArrowArrayMove(struct ArrowArray* src, struct ArrowArray* dest) {
90
+ assert(dest != src);
91
+ assert(!ArrowArrayIsReleased(src));
92
+ memcpy(dest, src, sizeof(struct ArrowArray));
93
+ ArrowArrayMarkReleased(src);
94
+ }
95
+
96
+ inline void ArrowDeviceArrayMove(struct ArrowDeviceArray* src,
97
+ struct ArrowDeviceArray* dest) {
98
+ assert(dest != src);
99
+ assert(!ArrowDeviceArrayIsReleased(src));
100
+ memcpy(dest, src, sizeof(struct ArrowDeviceArray));
101
+ ArrowDeviceArrayMarkReleased(src);
102
+ }
103
+
104
+ /// Release the C array, if necessary, by calling its release callback
105
+ inline void ArrowArrayRelease(struct ArrowArray* array) {
106
+ if (!ArrowArrayIsReleased(array)) {
107
+ array->release(array);
108
+ ARROW_C_ASSERT(ArrowArrayIsReleased(array),
109
+ "ArrowArrayRelease did not cleanup release callback");
110
+ }
111
+ }
112
+
113
+ inline void ArrowDeviceArrayRelease(struct ArrowDeviceArray* array) {
114
+ if (!ArrowDeviceArrayIsReleased(array)) {
115
+ array->array.release(&array->array);
116
+ ARROW_C_ASSERT(ArrowDeviceArrayIsReleased(array),
117
+ "ArrowDeviceArrayRelease did not cleanup release callback");
118
+ }
119
+ }
120
+
121
+ /// Query whether the C array stream is released
122
+ inline int ArrowArrayStreamIsReleased(const struct ArrowArrayStream* stream) {
123
+ return stream->release == NULL;
124
+ }
125
+
126
+ inline int ArrowDeviceArrayStreamIsReleased(const struct ArrowDeviceArrayStream* stream) {
127
+ return stream->release == NULL;
128
+ }
129
+
130
+ /// Mark the C array stream released (for use in release callbacks)
131
+ inline void ArrowArrayStreamMarkReleased(struct ArrowArrayStream* stream) {
132
+ stream->release = NULL;
133
+ }
134
+
135
+ inline void ArrowDeviceArrayStreamMarkReleased(struct ArrowDeviceArrayStream* stream) {
136
+ stream->release = NULL;
137
+ }
138
+
139
+ /// Move the C array stream from `src` to `dest`
140
+ ///
141
+ /// Note `dest` must *not* point to a valid stream already, otherwise there
142
+ /// will be a memory leak.
143
+ inline void ArrowArrayStreamMove(struct ArrowArrayStream* src,
144
+ struct ArrowArrayStream* dest) {
145
+ assert(dest != src);
146
+ assert(!ArrowArrayStreamIsReleased(src));
147
+ memcpy(dest, src, sizeof(struct ArrowArrayStream));
148
+ ArrowArrayStreamMarkReleased(src);
149
+ }
150
+
151
+ inline void ArrowDeviceArrayStreamMove(struct ArrowDeviceArrayStream* src,
152
+ struct ArrowDeviceArrayStream* dest) {
153
+ assert(dest != src);
154
+ assert(!ArrowDeviceArrayStreamIsReleased(src));
155
+ memcpy(dest, src, sizeof(struct ArrowDeviceArrayStream));
156
+ ArrowDeviceArrayStreamMarkReleased(src);
157
+ }
158
+
159
+ /// Release the C array stream, if necessary, by calling its release callback
160
+ inline void ArrowArrayStreamRelease(struct ArrowArrayStream* stream) {
161
+ if (!ArrowArrayStreamIsReleased(stream)) {
162
+ stream->release(stream);
163
+ ARROW_C_ASSERT(ArrowArrayStreamIsReleased(stream),
164
+ "ArrowArrayStreamRelease did not cleanup release callback");
165
+ }
166
+ }
167
+
168
+ inline void ArrowDeviceArrayStreamRelease(struct ArrowDeviceArrayStream* stream) {
169
+ if (!ArrowDeviceArrayStreamIsReleased(stream)) {
170
+ stream->release(stream);
171
+ ARROW_C_ASSERT(ArrowDeviceArrayStreamIsReleased(stream),
172
+ "ArrowDeviceArrayStreamRelease did not cleanup release callback");
173
+ }
174
+ }
175
+
176
+ #ifdef __cplusplus
177
+ }
178
+ #endif
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/compute/api_aggregate.h ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Eager evaluation convenience APIs for invoking common functions, including
19
+ // necessary memory allocations
20
+
21
+ #pragma once
22
+
23
+ #include <vector>
24
+
25
+ #include "arrow/compute/function_options.h"
26
+ #include "arrow/datum.h"
27
+ #include "arrow/result.h"
28
+ #include "arrow/util/macros.h"
29
+ #include "arrow/util/visibility.h"
30
+
31
+ namespace arrow {
32
+
33
+ class Array;
34
+
35
+ namespace compute {
36
+
37
+ class ExecContext;
38
+
39
+ // ----------------------------------------------------------------------
40
+ // Aggregate functions
41
+
42
+ /// \addtogroup compute-concrete-options
43
+ /// @{
44
+
45
+ /// \brief Control general scalar aggregate kernel behavior
46
+ ///
47
+ /// By default, null values are ignored (skip_nulls = true).
48
+ class ARROW_EXPORT ScalarAggregateOptions : public FunctionOptions {
49
+ public:
50
+ explicit ScalarAggregateOptions(bool skip_nulls = true, uint32_t min_count = 1);
51
+ static constexpr char const kTypeName[] = "ScalarAggregateOptions";
52
+ static ScalarAggregateOptions Defaults() { return ScalarAggregateOptions{}; }
53
+
54
+ /// If true (the default), null values are ignored. Otherwise, if any value is null,
55
+ /// emit null.
56
+ bool skip_nulls;
57
+ /// If less than this many non-null values are observed, emit null.
58
+ uint32_t min_count;
59
+ };
60
+
61
+ /// \brief Control count aggregate kernel behavior.
62
+ ///
63
+ /// By default, only non-null values are counted.
64
+ class ARROW_EXPORT CountOptions : public FunctionOptions {
65
+ public:
66
+ enum CountMode {
67
+ /// Count only non-null values.
68
+ ONLY_VALID = 0,
69
+ /// Count only null values.
70
+ ONLY_NULL,
71
+ /// Count both non-null and null values.
72
+ ALL,
73
+ };
74
+ explicit CountOptions(CountMode mode = CountMode::ONLY_VALID);
75
+ static constexpr char const kTypeName[] = "CountOptions";
76
+ static CountOptions Defaults() { return CountOptions{}; }
77
+
78
+ CountMode mode;
79
+ };
80
+
81
+ /// \brief Control Mode kernel behavior
82
+ ///
83
+ /// Returns top-n common values and counts.
84
+ /// By default, returns the most common value and count.
85
+ class ARROW_EXPORT ModeOptions : public FunctionOptions {
86
+ public:
87
+ explicit ModeOptions(int64_t n = 1, bool skip_nulls = true, uint32_t min_count = 0);
88
+ static constexpr char const kTypeName[] = "ModeOptions";
89
+ static ModeOptions Defaults() { return ModeOptions{}; }
90
+
91
+ int64_t n = 1;
92
+ /// If true (the default), null values are ignored. Otherwise, if any value is null,
93
+ /// emit null.
94
+ bool skip_nulls;
95
+ /// If less than this many non-null values are observed, emit null.
96
+ uint32_t min_count;
97
+ };
98
+
99
+ /// \brief Control Delta Degrees of Freedom (ddof) of Variance and Stddev kernel
100
+ ///
101
+ /// The divisor used in calculations is N - ddof, where N is the number of elements.
102
+ /// By default, ddof is zero, and population variance or stddev is returned.
103
+ class ARROW_EXPORT VarianceOptions : public FunctionOptions {
104
+ public:
105
+ explicit VarianceOptions(int ddof = 0, bool skip_nulls = true, uint32_t min_count = 0);
106
+ static constexpr char const kTypeName[] = "VarianceOptions";
107
+ static VarianceOptions Defaults() { return VarianceOptions{}; }
108
+
109
+ int ddof = 0;
110
+ /// If true (the default), null values are ignored. Otherwise, if any value is null,
111
+ /// emit null.
112
+ bool skip_nulls;
113
+ /// If less than this many non-null values are observed, emit null.
114
+ uint32_t min_count;
115
+ };
116
+
117
+ /// \brief Control Quantile kernel behavior
118
+ ///
119
+ /// By default, returns the median value.
120
+ class ARROW_EXPORT QuantileOptions : public FunctionOptions {
121
+ public:
122
+ /// Interpolation method to use when quantile lies between two data points
123
+ enum Interpolation {
124
+ LINEAR = 0,
125
+ LOWER,
126
+ HIGHER,
127
+ NEAREST,
128
+ MIDPOINT,
129
+ };
130
+
131
+ explicit QuantileOptions(double q = 0.5, enum Interpolation interpolation = LINEAR,
132
+ bool skip_nulls = true, uint32_t min_count = 0);
133
+
134
+ explicit QuantileOptions(std::vector<double> q,
135
+ enum Interpolation interpolation = LINEAR,
136
+ bool skip_nulls = true, uint32_t min_count = 0);
137
+
138
+ static constexpr char const kTypeName[] = "QuantileOptions";
139
+ static QuantileOptions Defaults() { return QuantileOptions{}; }
140
+
141
+ /// probability level of quantile must be between 0 and 1 inclusive
142
+ std::vector<double> q;
143
+ enum Interpolation interpolation;
144
+ /// If true (the default), null values are ignored. Otherwise, if any value is null,
145
+ /// emit null.
146
+ bool skip_nulls;
147
+ /// If less than this many non-null values are observed, emit null.
148
+ uint32_t min_count;
149
+ };
150
+
151
+ /// \brief Control TDigest approximate quantile kernel behavior
152
+ ///
153
+ /// By default, returns the median value.
154
+ class ARROW_EXPORT TDigestOptions : public FunctionOptions {
155
+ public:
156
+ explicit TDigestOptions(double q = 0.5, uint32_t delta = 100,
157
+ uint32_t buffer_size = 500, bool skip_nulls = true,
158
+ uint32_t min_count = 0);
159
+ explicit TDigestOptions(std::vector<double> q, uint32_t delta = 100,
160
+ uint32_t buffer_size = 500, bool skip_nulls = true,
161
+ uint32_t min_count = 0);
162
+ static constexpr char const kTypeName[] = "TDigestOptions";
163
+ static TDigestOptions Defaults() { return TDigestOptions{}; }
164
+
165
+ /// probability level of quantile must be between 0 and 1 inclusive
166
+ std::vector<double> q;
167
+ /// compression parameter, default 100
168
+ uint32_t delta;
169
+ /// input buffer size, default 500
170
+ uint32_t buffer_size;
171
+ /// If true (the default), null values are ignored. Otherwise, if any value is null,
172
+ /// emit null.
173
+ bool skip_nulls;
174
+ /// If less than this many non-null values are observed, emit null.
175
+ uint32_t min_count;
176
+ };
177
+
178
+ /// \brief Control Index kernel behavior
179
+ class ARROW_EXPORT IndexOptions : public FunctionOptions {
180
+ public:
181
+ explicit IndexOptions(std::shared_ptr<Scalar> value);
182
+ // Default constructor for serialization
183
+ IndexOptions();
184
+ static constexpr char const kTypeName[] = "IndexOptions";
185
+
186
+ std::shared_ptr<Scalar> value;
187
+ };
188
+
189
+ /// \brief Configure a grouped aggregation
190
+ struct ARROW_EXPORT Aggregate {
191
+ Aggregate() = default;
192
+
193
+ Aggregate(std::string function, std::shared_ptr<FunctionOptions> options,
194
+ std::vector<FieldRef> target, std::string name = "")
195
+ : function(std::move(function)),
196
+ options(std::move(options)),
197
+ target(std::move(target)),
198
+ name(std::move(name)) {}
199
+
200
+ Aggregate(std::string function, std::shared_ptr<FunctionOptions> options,
201
+ FieldRef target, std::string name = "")
202
+ : Aggregate(std::move(function), std::move(options),
203
+ std::vector<FieldRef>{std::move(target)}, std::move(name)) {}
204
+
205
+ Aggregate(std::string function, FieldRef target, std::string name)
206
+ : Aggregate(std::move(function), /*options=*/NULLPTR,
207
+ std::vector<FieldRef>{std::move(target)}, std::move(name)) {}
208
+
209
+ Aggregate(std::string function, std::string name)
210
+ : Aggregate(std::move(function), /*options=*/NULLPTR,
211
+ /*target=*/std::vector<FieldRef>{}, std::move(name)) {}
212
+
213
+ /// the name of the aggregation function
214
+ std::string function;
215
+
216
+ /// options for the aggregation function
217
+ std::shared_ptr<FunctionOptions> options;
218
+
219
+ /// zero or more fields to which aggregations will be applied
220
+ std::vector<FieldRef> target;
221
+
222
+ /// optional output field name for aggregations
223
+ std::string name;
224
+ };
225
+
226
+ /// @}
227
+
228
+ /// \brief Count values in an array.
229
+ ///
230
+ /// \param[in] options counting options, see CountOptions for more information
231
+ /// \param[in] datum to count
232
+ /// \param[in] ctx the function execution context, optional
233
+ /// \return out resulting datum
234
+ ///
235
+ /// \since 1.0.0
236
+ /// \note API not yet finalized
237
+ ARROW_EXPORT
238
+ Result<Datum> Count(const Datum& datum,
239
+ const CountOptions& options = CountOptions::Defaults(),
240
+ ExecContext* ctx = NULLPTR);
241
+
242
+ /// \brief Compute the mean of a numeric array.
243
+ ///
244
+ /// \param[in] value datum to compute the mean, expecting Array
245
+ /// \param[in] options see ScalarAggregateOptions for more information
246
+ /// \param[in] ctx the function execution context, optional
247
+ /// \return datum of the computed mean as a DoubleScalar
248
+ ///
249
+ /// \since 1.0.0
250
+ /// \note API not yet finalized
251
+ ARROW_EXPORT
252
+ Result<Datum> Mean(
253
+ const Datum& value,
254
+ const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(),
255
+ ExecContext* ctx = NULLPTR);
256
+
257
+ /// \brief Compute the product of values of a numeric array.
258
+ ///
259
+ /// \param[in] value datum to compute product of, expecting Array or ChunkedArray
260
+ /// \param[in] options see ScalarAggregateOptions for more information
261
+ /// \param[in] ctx the function execution context, optional
262
+ /// \return datum of the computed sum as a Scalar
263
+ ///
264
+ /// \since 6.0.0
265
+ /// \note API not yet finalized
266
+ ARROW_EXPORT
267
+ Result<Datum> Product(
268
+ const Datum& value,
269
+ const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(),
270
+ ExecContext* ctx = NULLPTR);
271
+
272
+ /// \brief Sum values of a numeric array.
273
+ ///
274
+ /// \param[in] value datum to sum, expecting Array or ChunkedArray
275
+ /// \param[in] options see ScalarAggregateOptions for more information
276
+ /// \param[in] ctx the function execution context, optional
277
+ /// \return datum of the computed sum as a Scalar
278
+ ///
279
+ /// \since 1.0.0
280
+ /// \note API not yet finalized
281
+ ARROW_EXPORT
282
+ Result<Datum> Sum(
283
+ const Datum& value,
284
+ const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(),
285
+ ExecContext* ctx = NULLPTR);
286
+
287
+ /// \brief Calculate the first value of an array
288
+ ///
289
+ /// \param[in] value input datum, expecting Array or ChunkedArray
290
+ /// \param[in] options see ScalarAggregateOptions for more information
291
+ /// \param[in] ctx the function execution context, optional
292
+ /// \return datum of the computed first as Scalar
293
+ ///
294
+ /// \since 13.0.0
295
+ /// \note API not yet finalized
296
+ ARROW_EXPORT
297
+ Result<Datum> First(
298
+ const Datum& value,
299
+ const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(),
300
+ ExecContext* ctx = NULLPTR);
301
+
302
+ /// \brief Calculate the last value of an array
303
+ ///
304
+ /// \param[in] value input datum, expecting Array or ChunkedArray
305
+ /// \param[in] options see ScalarAggregateOptions for more information
306
+ /// \param[in] ctx the function execution context, optional
307
+ /// \return datum of the computed last as a Scalar
308
+ ///
309
+ /// \since 13.0.0
310
+ /// \note API not yet finalized
311
+ ARROW_EXPORT
312
+ Result<Datum> Last(
313
+ const Datum& value,
314
+ const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(),
315
+ ExecContext* ctx = NULLPTR);
316
+
317
+ /// \brief Calculate the min / max of a numeric array
318
+ ///
319
+ /// This function returns both the min and max as a struct scalar, with type
320
+ /// struct<min: T, max: T>, where T is the input type
321
+ ///
322
+ /// \param[in] value input datum, expecting Array or ChunkedArray
323
+ /// \param[in] options see ScalarAggregateOptions for more information
324
+ /// \param[in] ctx the function execution context, optional
325
+ /// \return resulting datum as a struct<min: T, max: T> scalar
326
+ ///
327
+ /// \since 1.0.0
328
+ /// \note API not yet finalized
329
+ ARROW_EXPORT
330
+ Result<Datum> MinMax(
331
+ const Datum& value,
332
+ const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(),
333
+ ExecContext* ctx = NULLPTR);
334
+
335
+ /// \brief Test whether any element in a boolean array evaluates to true.
336
+ ///
337
+ /// This function returns true if any of the elements in the array evaluates
338
+ /// to true and false otherwise. Null values are ignored by default.
339
+ /// If null values are taken into account by setting ScalarAggregateOptions
340
+ /// parameter skip_nulls = false then Kleene logic is used.
341
+ /// See KleeneOr for more details on Kleene logic.
342
+ ///
343
+ /// \param[in] value input datum, expecting a boolean array
344
+ /// \param[in] options see ScalarAggregateOptions for more information
345
+ /// \param[in] ctx the function execution context, optional
346
+ /// \return resulting datum as a BooleanScalar
347
+ ///
348
+ /// \since 3.0.0
349
+ /// \note API not yet finalized
350
+ ARROW_EXPORT
351
+ Result<Datum> Any(
352
+ const Datum& value,
353
+ const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(),
354
+ ExecContext* ctx = NULLPTR);
355
+
356
+ /// \brief Test whether all elements in a boolean array evaluate to true.
357
+ ///
358
+ /// This function returns true if all of the elements in the array evaluate
359
+ /// to true and false otherwise. Null values are ignored by default.
360
+ /// If null values are taken into account by setting ScalarAggregateOptions
361
+ /// parameter skip_nulls = false then Kleene logic is used.
362
+ /// See KleeneAnd for more details on Kleene logic.
363
+ ///
364
+ /// \param[in] value input datum, expecting a boolean array
365
+ /// \param[in] options see ScalarAggregateOptions for more information
366
+ /// \param[in] ctx the function execution context, optional
367
+ /// \return resulting datum as a BooleanScalar
368
+
369
+ /// \since 3.0.0
370
+ /// \note API not yet finalized
371
+ ARROW_EXPORT
372
+ Result<Datum> All(
373
+ const Datum& value,
374
+ const ScalarAggregateOptions& options = ScalarAggregateOptions::Defaults(),
375
+ ExecContext* ctx = NULLPTR);
376
+
377
+ /// \brief Calculate the modal (most common) value of a numeric array
378
+ ///
379
+ /// This function returns top-n most common values and number of times they occur as
380
+ /// an array of `struct<mode: T, count: int64>`, where T is the input type.
381
+ /// Values with larger counts are returned before smaller ones.
382
+ /// If there are more than one values with same count, smaller value is returned first.
383
+ ///
384
+ /// \param[in] value input datum, expecting Array or ChunkedArray
385
+ /// \param[in] options see ModeOptions for more information
386
+ /// \param[in] ctx the function execution context, optional
387
+ /// \return resulting datum as an array of struct<mode: T, count: int64>
388
+ ///
389
+ /// \since 2.0.0
390
+ /// \note API not yet finalized
391
+ ARROW_EXPORT
392
+ Result<Datum> Mode(const Datum& value,
393
+ const ModeOptions& options = ModeOptions::Defaults(),
394
+ ExecContext* ctx = NULLPTR);
395
+
396
+ /// \brief Calculate the standard deviation of a numeric array
397
+ ///
398
+ /// \param[in] value input datum, expecting Array or ChunkedArray
399
+ /// \param[in] options see VarianceOptions for more information
400
+ /// \param[in] ctx the function execution context, optional
401
+ /// \return datum of the computed standard deviation as a DoubleScalar
402
+ ///
403
+ /// \since 2.0.0
404
+ /// \note API not yet finalized
405
+ ARROW_EXPORT
406
+ Result<Datum> Stddev(const Datum& value,
407
+ const VarianceOptions& options = VarianceOptions::Defaults(),
408
+ ExecContext* ctx = NULLPTR);
409
+
410
+ /// \brief Calculate the variance of a numeric array
411
+ ///
412
+ /// \param[in] value input datum, expecting Array or ChunkedArray
413
+ /// \param[in] options see VarianceOptions for more information
414
+ /// \param[in] ctx the function execution context, optional
415
+ /// \return datum of the computed variance as a DoubleScalar
416
+ ///
417
+ /// \since 2.0.0
418
+ /// \note API not yet finalized
419
+ ARROW_EXPORT
420
+ Result<Datum> Variance(const Datum& value,
421
+ const VarianceOptions& options = VarianceOptions::Defaults(),
422
+ ExecContext* ctx = NULLPTR);
423
+
424
+ /// \brief Calculate the quantiles of a numeric array
425
+ ///
426
+ /// \param[in] value input datum, expecting Array or ChunkedArray
427
+ /// \param[in] options see QuantileOptions for more information
428
+ /// \param[in] ctx the function execution context, optional
429
+ /// \return resulting datum as an array
430
+ ///
431
+ /// \since 4.0.0
432
+ /// \note API not yet finalized
433
+ ARROW_EXPORT
434
+ Result<Datum> Quantile(const Datum& value,
435
+ const QuantileOptions& options = QuantileOptions::Defaults(),
436
+ ExecContext* ctx = NULLPTR);
437
+
438
+ /// \brief Calculate the approximate quantiles of a numeric array with T-Digest algorithm
439
+ ///
440
+ /// \param[in] value input datum, expecting Array or ChunkedArray
441
+ /// \param[in] options see TDigestOptions for more information
442
+ /// \param[in] ctx the function execution context, optional
443
+ /// \return resulting datum as an array
444
+ ///
445
+ /// \since 4.0.0
446
+ /// \note API not yet finalized
447
+ ARROW_EXPORT
448
+ Result<Datum> TDigest(const Datum& value,
449
+ const TDigestOptions& options = TDigestOptions::Defaults(),
450
+ ExecContext* ctx = NULLPTR);
451
+
452
+ /// \brief Find the first index of a value in an array.
453
+ ///
454
+ /// \param[in] value The array to search.
455
+ /// \param[in] options The array to search for. See IndexOptions.
456
+ /// \param[in] ctx the function execution context, optional
457
+ /// \return out a Scalar containing the index (or -1 if not found).
458
+ ///
459
+ /// \since 5.0.0
460
+ /// \note API not yet finalized
461
+ ARROW_EXPORT
462
+ Result<Datum> Index(const Datum& value, const IndexOptions& options,
463
+ ExecContext* ctx = NULLPTR);
464
+
465
+ } // namespace compute
466
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/compute/api_scalar.h ADDED
@@ -0,0 +1,1722 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Eager evaluation convenience APIs for invoking common functions, including
19
+ // necessary memory allocations
20
+
21
+ #pragma once
22
+
23
+ #include <optional>
24
+ #include <string>
25
+ #include <utility>
26
+
27
+ #include "arrow/compute/function_options.h"
28
+ #include "arrow/compute/type_fwd.h"
29
+ #include "arrow/datum.h"
30
+ #include "arrow/result.h"
31
+ #include "arrow/util/macros.h"
32
+ #include "arrow/util/visibility.h"
33
+
34
+ namespace arrow {
35
+ namespace compute {
36
+
37
+ /// \addtogroup compute-concrete-options
38
+ ///
39
+ /// @{
40
+
41
+ class ARROW_EXPORT ArithmeticOptions : public FunctionOptions {
42
+ public:
43
+ explicit ArithmeticOptions(bool check_overflow = false);
44
+ static constexpr char const kTypeName[] = "ArithmeticOptions";
45
+ bool check_overflow;
46
+ };
47
+
48
+ class ARROW_EXPORT ElementWiseAggregateOptions : public FunctionOptions {
49
+ public:
50
+ explicit ElementWiseAggregateOptions(bool skip_nulls = true);
51
+ static constexpr char const kTypeName[] = "ElementWiseAggregateOptions";
52
+ static ElementWiseAggregateOptions Defaults() { return ElementWiseAggregateOptions{}; }
53
+ bool skip_nulls;
54
+ };
55
+
56
+ /// Rounding and tie-breaking modes for round compute functions.
57
+ /// Additional details and examples are provided in compute.rst.
58
+ enum class RoundMode : int8_t {
59
+ /// Round to nearest integer less than or equal in magnitude (aka "floor")
60
+ DOWN,
61
+ /// Round to nearest integer greater than or equal in magnitude (aka "ceil")
62
+ UP,
63
+ /// Get the integral part without fractional digits (aka "trunc")
64
+ TOWARDS_ZERO,
65
+ /// Round negative values with DOWN rule
66
+ /// and positive values with UP rule (aka "away from zero")
67
+ TOWARDS_INFINITY,
68
+ /// Round ties with DOWN rule (also called "round half towards negative infinity")
69
+ HALF_DOWN,
70
+ /// Round ties with UP rule (also called "round half towards positive infinity")
71
+ HALF_UP,
72
+ /// Round ties with TOWARDS_ZERO rule (also called "round half away from infinity")
73
+ HALF_TOWARDS_ZERO,
74
+ /// Round ties with TOWARDS_INFINITY rule (also called "round half away from zero")
75
+ HALF_TOWARDS_INFINITY,
76
+ /// Round ties to nearest even integer
77
+ HALF_TO_EVEN,
78
+ /// Round ties to nearest odd integer
79
+ HALF_TO_ODD,
80
+ };
81
+
82
+ class ARROW_EXPORT RoundOptions : public FunctionOptions {
83
+ public:
84
+ explicit RoundOptions(int64_t ndigits = 0,
85
+ RoundMode round_mode = RoundMode::HALF_TO_EVEN);
86
+ static constexpr char const kTypeName[] = "RoundOptions";
87
+ static RoundOptions Defaults() { return RoundOptions(); }
88
+ /// Rounding precision (number of digits to round to)
89
+ int64_t ndigits;
90
+ /// Rounding and tie-breaking mode
91
+ RoundMode round_mode;
92
+ };
93
+
94
+ class ARROW_EXPORT RoundBinaryOptions : public FunctionOptions {
95
+ public:
96
+ explicit RoundBinaryOptions(RoundMode round_mode = RoundMode::HALF_TO_EVEN);
97
+ static constexpr char const kTypeName[] = "RoundBinaryOptions";
98
+ static RoundBinaryOptions Defaults() { return RoundBinaryOptions(); }
99
+ /// Rounding and tie-breaking mode
100
+ RoundMode round_mode;
101
+ };
102
+
103
+ enum class CalendarUnit : int8_t {
104
+ NANOSECOND,
105
+ MICROSECOND,
106
+ MILLISECOND,
107
+ SECOND,
108
+ MINUTE,
109
+ HOUR,
110
+ DAY,
111
+ WEEK,
112
+ MONTH,
113
+ QUARTER,
114
+ YEAR
115
+ };
116
+
117
+ class ARROW_EXPORT RoundTemporalOptions : public FunctionOptions {
118
+ public:
119
+ explicit RoundTemporalOptions(int multiple = 1, CalendarUnit unit = CalendarUnit::DAY,
120
+ bool week_starts_monday = true,
121
+ bool ceil_is_strictly_greater = false,
122
+ bool calendar_based_origin = false);
123
+ static constexpr char const kTypeName[] = "RoundTemporalOptions";
124
+ static RoundTemporalOptions Defaults() { return RoundTemporalOptions(); }
125
+
126
+ /// Number of units to round to
127
+ int multiple;
128
+ /// The unit used for rounding of time
129
+ CalendarUnit unit;
130
+ /// What day does the week start with (Monday=true, Sunday=false)
131
+ bool week_starts_monday;
132
+ /// Enable this flag to return a rounded value that is strictly greater than the input.
133
+ /// For example: ceiling 1970-01-01T00:00:00 to 3 hours would yield 1970-01-01T03:00:00
134
+ /// if set to true and 1970-01-01T00:00:00 if set to false.
135
+ /// This applies for ceiling only.
136
+ bool ceil_is_strictly_greater;
137
+ /// By default time is rounded to a multiple of units since 1970-01-01T00:00:00.
138
+ /// By setting calendar_based_origin to true, time will be rounded to a number
139
+ /// of units since the last greater calendar unit.
140
+ /// For example: rounding to a multiple of days since the beginning of the month or
141
+ /// to hours since the beginning of the day.
142
+ /// Exceptions: week and quarter are not used as greater units, therefore days will
143
+ /// will be rounded to the beginning of the month not week. Greater unit of week
144
+ /// is year.
145
+ /// Note that ceiling and rounding might change sorting order of an array near greater
146
+ /// unit change. For example rounding YYYY-mm-dd 23:00:00 to 5 hours will ceil and
147
+ /// round to YYYY-mm-dd+1 01:00:00 and floor to YYYY-mm-dd 20:00:00. On the other hand
148
+ /// YYYY-mm-dd+1 00:00:00 will ceil, round and floor to YYYY-mm-dd+1 00:00:00. This
149
+ /// can break the order of an already ordered array.
150
+ bool calendar_based_origin;
151
+ };
152
+
153
+ class ARROW_EXPORT RoundToMultipleOptions : public FunctionOptions {
154
+ public:
155
+ explicit RoundToMultipleOptions(double multiple = 1.0,
156
+ RoundMode round_mode = RoundMode::HALF_TO_EVEN);
157
+ explicit RoundToMultipleOptions(std::shared_ptr<Scalar> multiple,
158
+ RoundMode round_mode = RoundMode::HALF_TO_EVEN);
159
+ static constexpr char const kTypeName[] = "RoundToMultipleOptions";
160
+ static RoundToMultipleOptions Defaults() { return RoundToMultipleOptions(); }
161
+ /// Rounding scale (multiple to round to).
162
+ ///
163
+ /// Should be a positive numeric scalar of a type compatible with the
164
+ /// argument to be rounded. The cast kernel is used to convert the rounding
165
+ /// multiple to match the result type.
166
+ std::shared_ptr<Scalar> multiple;
167
+ /// Rounding and tie-breaking mode
168
+ RoundMode round_mode;
169
+ };
170
+
171
+ /// Options for var_args_join.
172
+ class ARROW_EXPORT JoinOptions : public FunctionOptions {
173
+ public:
174
+ /// How to handle null values. (A null separator always results in a null output.)
175
+ enum NullHandlingBehavior {
176
+ /// A null in any input results in a null in the output.
177
+ EMIT_NULL,
178
+ /// Nulls in inputs are skipped.
179
+ SKIP,
180
+ /// Nulls in inputs are replaced with the replacement string.
181
+ REPLACE,
182
+ };
183
+ explicit JoinOptions(NullHandlingBehavior null_handling = EMIT_NULL,
184
+ std::string null_replacement = "");
185
+ static constexpr char const kTypeName[] = "JoinOptions";
186
+ static JoinOptions Defaults() { return JoinOptions(); }
187
+ NullHandlingBehavior null_handling;
188
+ std::string null_replacement;
189
+ };
190
+
191
+ class ARROW_EXPORT MatchSubstringOptions : public FunctionOptions {
192
+ public:
193
+ explicit MatchSubstringOptions(std::string pattern, bool ignore_case = false);
194
+ MatchSubstringOptions();
195
+ static constexpr char const kTypeName[] = "MatchSubstringOptions";
196
+
197
+ /// The exact substring (or regex, depending on kernel) to look for inside input values.
198
+ std::string pattern;
199
+ /// Whether to perform a case-insensitive match.
200
+ bool ignore_case;
201
+ };
202
+
203
+ class ARROW_EXPORT SplitOptions : public FunctionOptions {
204
+ public:
205
+ explicit SplitOptions(int64_t max_splits = -1, bool reverse = false);
206
+ static constexpr char const kTypeName[] = "SplitOptions";
207
+
208
+ /// Maximum number of splits allowed, or unlimited when -1
209
+ int64_t max_splits;
210
+ /// Start splitting from the end of the string (only relevant when max_splits != -1)
211
+ bool reverse;
212
+ };
213
+
214
+ class ARROW_EXPORT SplitPatternOptions : public FunctionOptions {
215
+ public:
216
+ explicit SplitPatternOptions(std::string pattern, int64_t max_splits = -1,
217
+ bool reverse = false);
218
+ SplitPatternOptions();
219
+ static constexpr char const kTypeName[] = "SplitPatternOptions";
220
+
221
+ /// The exact substring to split on.
222
+ std::string pattern;
223
+ /// Maximum number of splits allowed, or unlimited when -1
224
+ int64_t max_splits;
225
+ /// Start splitting from the end of the string (only relevant when max_splits != -1)
226
+ bool reverse;
227
+ };
228
+
229
+ class ARROW_EXPORT ReplaceSliceOptions : public FunctionOptions {
230
+ public:
231
+ explicit ReplaceSliceOptions(int64_t start, int64_t stop, std::string replacement);
232
+ ReplaceSliceOptions();
233
+ static constexpr char const kTypeName[] = "ReplaceSliceOptions";
234
+
235
+ /// Index to start slicing at
236
+ int64_t start;
237
+ /// Index to stop slicing at
238
+ int64_t stop;
239
+ /// String to replace the slice with
240
+ std::string replacement;
241
+ };
242
+
243
+ class ARROW_EXPORT ReplaceSubstringOptions : public FunctionOptions {
244
+ public:
245
+ explicit ReplaceSubstringOptions(std::string pattern, std::string replacement,
246
+ int64_t max_replacements = -1);
247
+ ReplaceSubstringOptions();
248
+ static constexpr char const kTypeName[] = "ReplaceSubstringOptions";
249
+
250
+ /// Pattern to match, literal, or regular expression depending on which kernel is used
251
+ std::string pattern;
252
+ /// String to replace the pattern with
253
+ std::string replacement;
254
+ /// Max number of substrings to replace (-1 means unbounded)
255
+ int64_t max_replacements;
256
+ };
257
+
258
+ class ARROW_EXPORT ExtractRegexOptions : public FunctionOptions {
259
+ public:
260
+ explicit ExtractRegexOptions(std::string pattern);
261
+ ExtractRegexOptions();
262
+ static constexpr char const kTypeName[] = "ExtractRegexOptions";
263
+
264
+ /// Regular expression with named capture fields
265
+ std::string pattern;
266
+ };
267
+
268
+ /// Options for IsIn and IndexIn functions
269
+ class ARROW_EXPORT SetLookupOptions : public FunctionOptions {
270
+ public:
271
+ /// How to handle null values.
272
+ enum NullMatchingBehavior {
273
+ /// MATCH, any null in `value_set` is successfully matched in
274
+ /// the input.
275
+ MATCH,
276
+ /// SKIP, any null in `value_set` is ignored and nulls in the input
277
+ /// produce null (IndexIn) or false (IsIn) values in the output.
278
+ SKIP,
279
+ /// EMIT_NULL, any null in `value_set` is ignored and nulls in the
280
+ /// input produce null (IndexIn and IsIn) values in the output.
281
+ EMIT_NULL,
282
+ /// INCONCLUSIVE, null values are regarded as unknown values, which is
283
+ /// sql-compatible. nulls in the input produce null (IndexIn and IsIn)
284
+ /// values in the output. Besides, if `value_set` contains a null,
285
+ /// non-null unmatched values in the input also produce null values
286
+ /// (IndexIn and IsIn) in the output.
287
+ INCONCLUSIVE
288
+ };
289
+
290
+ explicit SetLookupOptions(Datum value_set, NullMatchingBehavior = MATCH);
291
+ SetLookupOptions();
292
+
293
+ // DEPRECATED(will be removed after removing of skip_nulls)
294
+ explicit SetLookupOptions(Datum value_set, bool skip_nulls);
295
+
296
+ static constexpr char const kTypeName[] = "SetLookupOptions";
297
+
298
+ /// The set of values to look up input values into.
299
+ Datum value_set;
300
+
301
+ NullMatchingBehavior null_matching_behavior;
302
+
303
+ // DEPRECATED(will be removed after removing of skip_nulls)
304
+ NullMatchingBehavior GetNullMatchingBehavior() const;
305
+
306
+ // DEPRECATED(use null_matching_behavior instead)
307
+ /// Whether nulls in `value_set` count for lookup.
308
+ ///
309
+ /// If true, any null in `value_set` is ignored and nulls in the input
310
+ /// produce null (IndexIn) or false (IsIn) values in the output.
311
+ /// If false, any null in `value_set` is successfully matched in
312
+ /// the input.
313
+ std::optional<bool> skip_nulls;
314
+ };
315
+
316
+ /// Options for struct_field function
317
+ class ARROW_EXPORT StructFieldOptions : public FunctionOptions {
318
+ public:
319
+ explicit StructFieldOptions(std::vector<int> indices);
320
+ explicit StructFieldOptions(std::initializer_list<int>);
321
+ explicit StructFieldOptions(FieldRef field_ref);
322
+ StructFieldOptions();
323
+ static constexpr char const kTypeName[] = "StructFieldOptions";
324
+
325
+ /// The FieldRef specifying what to extract from struct or union.
326
+ FieldRef field_ref;
327
+ };
328
+
329
+ class ARROW_EXPORT StrptimeOptions : public FunctionOptions {
330
+ public:
331
+ explicit StrptimeOptions(std::string format, TimeUnit::type unit,
332
+ bool error_is_null = false);
333
+ StrptimeOptions();
334
+ static constexpr char const kTypeName[] = "StrptimeOptions";
335
+
336
+ /// The desired format string.
337
+ std::string format;
338
+ /// The desired time resolution
339
+ TimeUnit::type unit;
340
+ /// Return null on parsing errors if true or raise if false
341
+ bool error_is_null;
342
+ };
343
+
344
+ class ARROW_EXPORT StrftimeOptions : public FunctionOptions {
345
+ public:
346
+ explicit StrftimeOptions(std::string format, std::string locale = "C");
347
+ StrftimeOptions();
348
+
349
+ static constexpr char const kTypeName[] = "StrftimeOptions";
350
+
351
+ static constexpr const char* kDefaultFormat = "%Y-%m-%dT%H:%M:%S";
352
+
353
+ /// The desired format string.
354
+ std::string format;
355
+ /// The desired output locale string.
356
+ std::string locale;
357
+ };
358
+
359
+ class ARROW_EXPORT PadOptions : public FunctionOptions {
360
+ public:
361
+ explicit PadOptions(int64_t width, std::string padding = " ",
362
+ bool lean_left_on_odd_padding = true);
363
+ PadOptions();
364
+ static constexpr char const kTypeName[] = "PadOptions";
365
+
366
+ /// The desired string length.
367
+ int64_t width;
368
+ /// What to pad the string with. Should be one codepoint (Unicode)/byte (ASCII).
369
+ std::string padding;
370
+ /// What to do if there is an odd number of padding characters (in case of centered
371
+ /// padding). Defaults to aligning on the left (i.e. adding the extra padding character
372
+ /// on the right)
373
+ bool lean_left_on_odd_padding = true;
374
+ };
375
+
376
+ class ARROW_EXPORT TrimOptions : public FunctionOptions {
377
+ public:
378
+ explicit TrimOptions(std::string characters);
379
+ TrimOptions();
380
+ static constexpr char const kTypeName[] = "TrimOptions";
381
+
382
+ /// The individual characters to be trimmed from the string.
383
+ std::string characters;
384
+ };
385
+
386
+ class ARROW_EXPORT SliceOptions : public FunctionOptions {
387
+ public:
388
+ explicit SliceOptions(int64_t start, int64_t stop = std::numeric_limits<int64_t>::max(),
389
+ int64_t step = 1);
390
+ SliceOptions();
391
+ static constexpr char const kTypeName[] = "SliceOptions";
392
+ int64_t start, stop, step;
393
+ };
394
+
395
+ class ARROW_EXPORT ListSliceOptions : public FunctionOptions {
396
+ public:
397
+ explicit ListSliceOptions(int64_t start, std::optional<int64_t> stop = std::nullopt,
398
+ int64_t step = 1,
399
+ std::optional<bool> return_fixed_size_list = std::nullopt);
400
+ ListSliceOptions();
401
+ static constexpr char const kTypeName[] = "ListSliceOptions";
402
+ /// The start of list slicing.
403
+ int64_t start;
404
+ /// Optional stop of list slicing. If not set, then slice to end. (NotImplemented)
405
+ std::optional<int64_t> stop;
406
+ /// Slicing step
407
+ int64_t step;
408
+ // Whether to return a FixedSizeListArray. If true _and_ stop is after
409
+ // a list element's length, nulls will be appended to create the requested slice size.
410
+ // Default of `nullopt` will return whatever type it got in.
411
+ std::optional<bool> return_fixed_size_list;
412
+ };
413
+
414
+ class ARROW_EXPORT NullOptions : public FunctionOptions {
415
+ public:
416
+ explicit NullOptions(bool nan_is_null = false);
417
+ static constexpr char const kTypeName[] = "NullOptions";
418
+ static NullOptions Defaults() { return NullOptions{}; }
419
+
420
+ bool nan_is_null;
421
+ };
422
+
423
+ enum CompareOperator : int8_t {
424
+ EQUAL,
425
+ NOT_EQUAL,
426
+ GREATER,
427
+ GREATER_EQUAL,
428
+ LESS,
429
+ LESS_EQUAL,
430
+ };
431
+
432
+ struct ARROW_EXPORT CompareOptions {
433
+ explicit CompareOptions(CompareOperator op) : op(op) {}
434
+ CompareOptions() : CompareOptions(CompareOperator::EQUAL) {}
435
+ enum CompareOperator op;
436
+ };
437
+
438
+ class ARROW_EXPORT MakeStructOptions : public FunctionOptions {
439
+ public:
440
+ MakeStructOptions(std::vector<std::string> n, std::vector<bool> r,
441
+ std::vector<std::shared_ptr<const KeyValueMetadata>> m);
442
+ explicit MakeStructOptions(std::vector<std::string> n);
443
+ MakeStructOptions();
444
+ static constexpr char const kTypeName[] = "MakeStructOptions";
445
+
446
+ /// Names for wrapped columns
447
+ std::vector<std::string> field_names;
448
+
449
+ /// Nullability bits for wrapped columns
450
+ std::vector<bool> field_nullability;
451
+
452
+ /// Metadata attached to wrapped columns
453
+ std::vector<std::shared_ptr<const KeyValueMetadata>> field_metadata;
454
+ };
455
+
456
+ struct ARROW_EXPORT DayOfWeekOptions : public FunctionOptions {
457
+ public:
458
+ explicit DayOfWeekOptions(bool count_from_zero = true, uint32_t week_start = 1);
459
+ static constexpr char const kTypeName[] = "DayOfWeekOptions";
460
+ static DayOfWeekOptions Defaults() { return DayOfWeekOptions(); }
461
+
462
+ /// Number days from 0 if true and from 1 if false
463
+ bool count_from_zero;
464
+ /// What day does the week start with (Monday=1, Sunday=7).
465
+ /// The numbering is unaffected by the count_from_zero parameter.
466
+ uint32_t week_start;
467
+ };
468
+
469
+ /// Used to control timestamp timezone conversion and handling ambiguous/nonexistent
470
+ /// times.
471
+ struct ARROW_EXPORT AssumeTimezoneOptions : public FunctionOptions {
472
+ public:
473
+ /// \brief How to interpret ambiguous local times that can be interpreted as
474
+ /// multiple instants (normally two) due to DST shifts.
475
+ ///
476
+ /// AMBIGUOUS_EARLIEST emits the earliest instant amongst possible interpretations.
477
+ /// AMBIGUOUS_LATEST emits the latest instant amongst possible interpretations.
478
+ enum Ambiguous { AMBIGUOUS_RAISE, AMBIGUOUS_EARLIEST, AMBIGUOUS_LATEST };
479
+
480
+ /// \brief How to handle local times that do not exist due to DST shifts.
481
+ ///
482
+ /// NONEXISTENT_EARLIEST emits the instant "just before" the DST shift instant
483
+ /// in the given timestamp precision (for example, for a nanoseconds precision
484
+ /// timestamp, this is one nanosecond before the DST shift instant).
485
+ /// NONEXISTENT_LATEST emits the DST shift instant.
486
+ enum Nonexistent { NONEXISTENT_RAISE, NONEXISTENT_EARLIEST, NONEXISTENT_LATEST };
487
+
488
+ explicit AssumeTimezoneOptions(std::string timezone,
489
+ Ambiguous ambiguous = AMBIGUOUS_RAISE,
490
+ Nonexistent nonexistent = NONEXISTENT_RAISE);
491
+ AssumeTimezoneOptions();
492
+ static constexpr char const kTypeName[] = "AssumeTimezoneOptions";
493
+
494
+ /// Timezone to convert timestamps from
495
+ std::string timezone;
496
+
497
+ /// How to interpret ambiguous local times (due to DST shifts)
498
+ Ambiguous ambiguous;
499
+ /// How to interpret nonexistent local times (due to DST shifts)
500
+ Nonexistent nonexistent;
501
+ };
502
+
503
+ struct ARROW_EXPORT WeekOptions : public FunctionOptions {
504
+ public:
505
+ explicit WeekOptions(bool week_starts_monday = true, bool count_from_zero = false,
506
+ bool first_week_is_fully_in_year = false);
507
+ static constexpr char const kTypeName[] = "WeekOptions";
508
+ static WeekOptions Defaults() { return WeekOptions{}; }
509
+ static WeekOptions ISODefaults() {
510
+ return WeekOptions{/*week_starts_monday*/ true,
511
+ /*count_from_zero=*/false,
512
+ /*first_week_is_fully_in_year=*/false};
513
+ }
514
+ static WeekOptions USDefaults() {
515
+ return WeekOptions{/*week_starts_monday*/ false,
516
+ /*count_from_zero=*/false,
517
+ /*first_week_is_fully_in_year=*/false};
518
+ }
519
+
520
+ /// What day does the week start with (Monday=true, Sunday=false)
521
+ bool week_starts_monday;
522
+ /// Dates from current year that fall into last ISO week of the previous year return
523
+ /// 0 if true and 52 or 53 if false.
524
+ bool count_from_zero;
525
+ /// Must the first week be fully in January (true), or is a week that begins on
526
+ /// December 29, 30, or 31 considered to be the first week of the new year (false)?
527
+ bool first_week_is_fully_in_year;
528
+ };
529
+
530
+ struct ARROW_EXPORT Utf8NormalizeOptions : public FunctionOptions {
531
+ public:
532
+ enum Form { NFC, NFKC, NFD, NFKD };
533
+
534
+ explicit Utf8NormalizeOptions(Form form = NFC);
535
+ static Utf8NormalizeOptions Defaults() { return Utf8NormalizeOptions(); }
536
+ static constexpr char const kTypeName[] = "Utf8NormalizeOptions";
537
+
538
+ /// The Unicode normalization form to apply
539
+ Form form;
540
+ };
541
+
542
+ class ARROW_EXPORT RandomOptions : public FunctionOptions {
543
+ public:
544
+ enum Initializer { SystemRandom, Seed };
545
+
546
+ static RandomOptions FromSystemRandom() { return RandomOptions{SystemRandom, 0}; }
547
+ static RandomOptions FromSeed(uint64_t seed) { return RandomOptions{Seed, seed}; }
548
+
549
+ RandomOptions(Initializer initializer, uint64_t seed);
550
+ RandomOptions();
551
+ static constexpr char const kTypeName[] = "RandomOptions";
552
+ static RandomOptions Defaults() { return RandomOptions(); }
553
+
554
+ /// The type of initialization for random number generation - system or provided seed.
555
+ Initializer initializer;
556
+ /// The seed value used to initialize the random number generation.
557
+ uint64_t seed;
558
+ };
559
+
560
+ /// Options for map_lookup function
561
+ class ARROW_EXPORT MapLookupOptions : public FunctionOptions {
562
+ public:
563
+ enum Occurrence {
564
+ /// Return the first matching value
565
+ FIRST,
566
+ /// Return the last matching value
567
+ LAST,
568
+ /// Return all matching values
569
+ ALL
570
+ };
571
+
572
+ explicit MapLookupOptions(std::shared_ptr<Scalar> query_key, Occurrence occurrence);
573
+ MapLookupOptions();
574
+
575
+ constexpr static char const kTypeName[] = "MapLookupOptions";
576
+
577
+ /// The key to lookup in the map
578
+ std::shared_ptr<Scalar> query_key;
579
+
580
+ /// Whether to return the first, last, or all matching values
581
+ Occurrence occurrence;
582
+ };
583
+
584
+ /// @}
585
+
586
+ /// \brief Get the absolute value of a value.
587
+ ///
588
+ /// If argument is null the result will be null.
589
+ ///
590
+ /// \param[in] arg the value transformed
591
+ /// \param[in] options arithmetic options (overflow handling), optional
592
+ /// \param[in] ctx the function execution context, optional
593
+ /// \return the elementwise absolute value
594
+ ARROW_EXPORT
595
+ Result<Datum> AbsoluteValue(const Datum& arg,
596
+ ArithmeticOptions options = ArithmeticOptions(),
597
+ ExecContext* ctx = NULLPTR);
598
+
599
+ /// \brief Add two values together. Array values must be the same length. If
600
+ /// either addend is null the result will be null.
601
+ ///
602
+ /// \param[in] left the first addend
603
+ /// \param[in] right the second addend
604
+ /// \param[in] options arithmetic options (overflow handling), optional
605
+ /// \param[in] ctx the function execution context, optional
606
+ /// \return the elementwise sum
607
+ ARROW_EXPORT
608
+ Result<Datum> Add(const Datum& left, const Datum& right,
609
+ ArithmeticOptions options = ArithmeticOptions(),
610
+ ExecContext* ctx = NULLPTR);
611
+
612
+ /// \brief Subtract two values. Array values must be the same length. If the
613
+ /// minuend or subtrahend is null the result will be null.
614
+ ///
615
+ /// \param[in] left the value subtracted from (minuend)
616
+ /// \param[in] right the value by which the minuend is reduced (subtrahend)
617
+ /// \param[in] options arithmetic options (overflow handling), optional
618
+ /// \param[in] ctx the function execution context, optional
619
+ /// \return the elementwise difference
620
+ ARROW_EXPORT
621
+ Result<Datum> Subtract(const Datum& left, const Datum& right,
622
+ ArithmeticOptions options = ArithmeticOptions(),
623
+ ExecContext* ctx = NULLPTR);
624
+
625
+ /// \brief Multiply two values. Array values must be the same length. If either
626
+ /// factor is null the result will be null.
627
+ ///
628
+ /// \param[in] left the first factor
629
+ /// \param[in] right the second factor
630
+ /// \param[in] options arithmetic options (overflow handling), optional
631
+ /// \param[in] ctx the function execution context, optional
632
+ /// \return the elementwise product
633
+ ARROW_EXPORT
634
+ Result<Datum> Multiply(const Datum& left, const Datum& right,
635
+ ArithmeticOptions options = ArithmeticOptions(),
636
+ ExecContext* ctx = NULLPTR);
637
+
638
+ /// \brief Divide two values. Array values must be the same length. If either
639
+ /// argument is null the result will be null. For integer types, if there is
640
+ /// a zero divisor, an error will be raised.
641
+ ///
642
+ /// \param[in] left the dividend
643
+ /// \param[in] right the divisor
644
+ /// \param[in] options arithmetic options (enable/disable overflow checking), optional
645
+ /// \param[in] ctx the function execution context, optional
646
+ /// \return the elementwise quotient
647
+ ARROW_EXPORT
648
+ Result<Datum> Divide(const Datum& left, const Datum& right,
649
+ ArithmeticOptions options = ArithmeticOptions(),
650
+ ExecContext* ctx = NULLPTR);
651
+
652
+ /// \brief Negate values.
653
+ ///
654
+ /// If argument is null the result will be null.
655
+ ///
656
+ /// \param[in] arg the value negated
657
+ /// \param[in] options arithmetic options (overflow handling), optional
658
+ /// \param[in] ctx the function execution context, optional
659
+ /// \return the elementwise negation
660
+ ARROW_EXPORT
661
+ Result<Datum> Negate(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(),
662
+ ExecContext* ctx = NULLPTR);
663
+
664
+ /// \brief Raise the values of base array to the power of the exponent array values.
665
+ /// Array values must be the same length. If either base or exponent is null the result
666
+ /// will be null.
667
+ ///
668
+ /// \param[in] left the base
669
+ /// \param[in] right the exponent
670
+ /// \param[in] options arithmetic options (enable/disable overflow checking), optional
671
+ /// \param[in] ctx the function execution context, optional
672
+ /// \return the elementwise base value raised to the power of exponent
673
+ ARROW_EXPORT
674
+ Result<Datum> Power(const Datum& left, const Datum& right,
675
+ ArithmeticOptions options = ArithmeticOptions(),
676
+ ExecContext* ctx = NULLPTR);
677
+
678
+ /// \brief Raise Euler's number to the power of specified exponent, element-wise.
679
+ /// If the exponent value is null the result will be null.
680
+ ///
681
+ /// \param[in] arg the exponent
682
+ /// \param[in] ctx the function execution context, optional
683
+ /// \return the element-wise Euler's number raised to the power of exponent
684
+ ARROW_EXPORT
685
+ Result<Datum> Exp(const Datum& arg, ExecContext* ctx = NULLPTR);
686
+
687
+ /// \brief Left shift the left array by the right array. Array values must be the
688
+ /// same length. If either operand is null, the result will be null.
689
+ ///
690
+ /// \param[in] left the value to shift
691
+ /// \param[in] right the value to shift by
692
+ /// \param[in] options arithmetic options (enable/disable overflow checking), optional
693
+ /// \param[in] ctx the function execution context, optional
694
+ /// \return the elementwise left value shifted left by the right value
695
+ ARROW_EXPORT
696
+ Result<Datum> ShiftLeft(const Datum& left, const Datum& right,
697
+ ArithmeticOptions options = ArithmeticOptions(),
698
+ ExecContext* ctx = NULLPTR);
699
+
700
+ /// \brief Right shift the left array by the right array. Array values must be the
701
+ /// same length. If either operand is null, the result will be null. Performs a
702
+ /// logical shift for unsigned values, and an arithmetic shift for signed values.
703
+ ///
704
+ /// \param[in] left the value to shift
705
+ /// \param[in] right the value to shift by
706
+ /// \param[in] options arithmetic options (enable/disable overflow checking), optional
707
+ /// \param[in] ctx the function execution context, optional
708
+ /// \return the elementwise left value shifted right by the right value
709
+ ARROW_EXPORT
710
+ Result<Datum> ShiftRight(const Datum& left, const Datum& right,
711
+ ArithmeticOptions options = ArithmeticOptions(),
712
+ ExecContext* ctx = NULLPTR);
713
+
714
+ /// \brief Compute the sine of the array values.
715
+ /// \param[in] arg The values to compute the sine for.
716
+ /// \param[in] options arithmetic options (enable/disable overflow checking), optional
717
+ /// \param[in] ctx the function execution context, optional
718
+ /// \return the elementwise sine of the values
719
+ ARROW_EXPORT
720
+ Result<Datum> Sin(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(),
721
+ ExecContext* ctx = NULLPTR);
722
+
723
+ /// \brief Compute the cosine of the array values.
724
+ /// \param[in] arg The values to compute the cosine for.
725
+ /// \param[in] options arithmetic options (enable/disable overflow checking), optional
726
+ /// \param[in] ctx the function execution context, optional
727
+ /// \return the elementwise cosine of the values
728
+ ARROW_EXPORT
729
+ Result<Datum> Cos(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(),
730
+ ExecContext* ctx = NULLPTR);
731
+
732
+ /// \brief Compute the inverse sine (arcsine) of the array values.
733
+ /// \param[in] arg The values to compute the inverse sine for.
734
+ /// \param[in] options arithmetic options (enable/disable overflow checking), optional
735
+ /// \param[in] ctx the function execution context, optional
736
+ /// \return the elementwise inverse sine of the values
737
+ ARROW_EXPORT
738
+ Result<Datum> Asin(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(),
739
+ ExecContext* ctx = NULLPTR);
740
+
741
+ /// \brief Compute the inverse cosine (arccosine) of the array values.
742
+ /// \param[in] arg The values to compute the inverse cosine for.
743
+ /// \param[in] options arithmetic options (enable/disable overflow checking), optional
744
+ /// \param[in] ctx the function execution context, optional
745
+ /// \return the elementwise inverse cosine of the values
746
+ ARROW_EXPORT
747
+ Result<Datum> Acos(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(),
748
+ ExecContext* ctx = NULLPTR);
749
+
750
+ /// \brief Compute the tangent of the array values.
751
+ /// \param[in] arg The values to compute the tangent for.
752
+ /// \param[in] options arithmetic options (enable/disable overflow checking), optional
753
+ /// \param[in] ctx the function execution context, optional
754
+ /// \return the elementwise tangent of the values
755
+ ARROW_EXPORT
756
+ Result<Datum> Tan(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(),
757
+ ExecContext* ctx = NULLPTR);
758
+
759
+ /// \brief Compute the inverse tangent (arctangent) of the array values.
760
+ /// \param[in] arg The values to compute the inverse tangent for.
761
+ /// \param[in] ctx the function execution context, optional
762
+ /// \return the elementwise inverse tangent of the values
763
+ ARROW_EXPORT
764
+ Result<Datum> Atan(const Datum& arg, ExecContext* ctx = NULLPTR);
765
+
766
+ /// \brief Compute the inverse tangent (arctangent) of y/x, using the
767
+ /// argument signs to determine the correct quadrant.
768
+ /// \param[in] y The y-values to compute the inverse tangent for.
769
+ /// \param[in] x The x-values to compute the inverse tangent for.
770
+ /// \param[in] ctx the function execution context, optional
771
+ /// \return the elementwise inverse tangent of the values
772
+ ARROW_EXPORT
773
+ Result<Datum> Atan2(const Datum& y, const Datum& x, ExecContext* ctx = NULLPTR);
774
+
775
+ /// \brief Get the natural log of a value.
776
+ ///
777
+ /// If argument is null the result will be null.
778
+ ///
779
+ /// \param[in] arg The values to compute the logarithm for.
780
+ /// \param[in] options arithmetic options (overflow handling), optional
781
+ /// \param[in] ctx the function execution context, optional
782
+ /// \return the elementwise natural log
783
+ ARROW_EXPORT
784
+ Result<Datum> Ln(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(),
785
+ ExecContext* ctx = NULLPTR);
786
+
787
+ /// \brief Get the log base 10 of a value.
788
+ ///
789
+ /// If argument is null the result will be null.
790
+ ///
791
+ /// \param[in] arg The values to compute the logarithm for.
792
+ /// \param[in] options arithmetic options (overflow handling), optional
793
+ /// \param[in] ctx the function execution context, optional
794
+ /// \return the elementwise log base 10
795
+ ARROW_EXPORT
796
+ Result<Datum> Log10(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(),
797
+ ExecContext* ctx = NULLPTR);
798
+
799
+ /// \brief Get the log base 2 of a value.
800
+ ///
801
+ /// If argument is null the result will be null.
802
+ ///
803
+ /// \param[in] arg The values to compute the logarithm for.
804
+ /// \param[in] options arithmetic options (overflow handling), optional
805
+ /// \param[in] ctx the function execution context, optional
806
+ /// \return the elementwise log base 2
807
+ ARROW_EXPORT
808
+ Result<Datum> Log2(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(),
809
+ ExecContext* ctx = NULLPTR);
810
+
811
+ /// \brief Get the natural log of (1 + value).
812
+ ///
813
+ /// If argument is null the result will be null.
814
+ /// This function may be more accurate than Log(1 + value) for values close to zero.
815
+ ///
816
+ /// \param[in] arg The values to compute the logarithm for.
817
+ /// \param[in] options arithmetic options (overflow handling), optional
818
+ /// \param[in] ctx the function execution context, optional
819
+ /// \return the elementwise natural log
820
+ ARROW_EXPORT
821
+ Result<Datum> Log1p(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(),
822
+ ExecContext* ctx = NULLPTR);
823
+
824
+ /// \brief Get the log of a value to the given base.
825
+ ///
826
+ /// If argument is null the result will be null.
827
+ ///
828
+ /// \param[in] arg The values to compute the logarithm for.
829
+ /// \param[in] base The given base.
830
+ /// \param[in] options arithmetic options (overflow handling), optional
831
+ /// \param[in] ctx the function execution context, optional
832
+ /// \return the elementwise log to the given base
833
+ ARROW_EXPORT
834
+ Result<Datum> Logb(const Datum& arg, const Datum& base,
835
+ ArithmeticOptions options = ArithmeticOptions(),
836
+ ExecContext* ctx = NULLPTR);
837
+
838
+ /// \brief Get the square-root of a value.
839
+ ///
840
+ /// If argument is null the result will be null.
841
+ ///
842
+ /// \param[in] arg The values to compute the square-root for.
843
+ /// \param[in] options arithmetic options (overflow handling), optional
844
+ /// \param[in] ctx the function execution context, optional
845
+ /// \return the elementwise square-root
846
+ ARROW_EXPORT
847
+ Result<Datum> Sqrt(const Datum& arg, ArithmeticOptions options = ArithmeticOptions(),
848
+ ExecContext* ctx = NULLPTR);
849
+
850
+ /// \brief Round to the nearest integer less than or equal in magnitude to the
851
+ /// argument.
852
+ ///
853
+ /// If argument is null the result will be null.
854
+ ///
855
+ /// \param[in] arg the value to round
856
+ /// \param[in] ctx the function execution context, optional
857
+ /// \return the rounded value
858
+ ARROW_EXPORT
859
+ Result<Datum> Floor(const Datum& arg, ExecContext* ctx = NULLPTR);
860
+
861
+ /// \brief Round to the nearest integer greater than or equal in magnitude to the
862
+ /// argument.
863
+ ///
864
+ /// If argument is null the result will be null.
865
+ ///
866
+ /// \param[in] arg the value to round
867
+ /// \param[in] ctx the function execution context, optional
868
+ /// \return the rounded value
869
+ ARROW_EXPORT
870
+ Result<Datum> Ceil(const Datum& arg, ExecContext* ctx = NULLPTR);
871
+
872
+ /// \brief Get the integral part without fractional digits.
873
+ ///
874
+ /// If argument is null the result will be null.
875
+ ///
876
+ /// \param[in] arg the value to truncate
877
+ /// \param[in] ctx the function execution context, optional
878
+ /// \return the truncated value
879
+ ARROW_EXPORT
880
+ Result<Datum> Trunc(const Datum& arg, ExecContext* ctx = NULLPTR);
881
+
882
+ /// \brief Find the element-wise maximum of any number of arrays or scalars.
883
+ /// Array values must be the same length.
884
+ ///
885
+ /// \param[in] args arrays or scalars to operate on.
886
+ /// \param[in] options options for handling nulls, optional
887
+ /// \param[in] ctx the function execution context, optional
888
+ /// \return the element-wise maximum
889
+ ARROW_EXPORT
890
+ Result<Datum> MaxElementWise(
891
+ const std::vector<Datum>& args,
892
+ ElementWiseAggregateOptions options = ElementWiseAggregateOptions::Defaults(),
893
+ ExecContext* ctx = NULLPTR);
894
+
895
+ /// \brief Find the element-wise minimum of any number of arrays or scalars.
896
+ /// Array values must be the same length.
897
+ ///
898
+ /// \param[in] args arrays or scalars to operate on.
899
+ /// \param[in] options options for handling nulls, optional
900
+ /// \param[in] ctx the function execution context, optional
901
+ /// \return the element-wise minimum
902
+ ARROW_EXPORT
903
+ Result<Datum> MinElementWise(
904
+ const std::vector<Datum>& args,
905
+ ElementWiseAggregateOptions options = ElementWiseAggregateOptions::Defaults(),
906
+ ExecContext* ctx = NULLPTR);
907
+
908
+ /// \brief Get the sign of a value. Array values can be of arbitrary length. If argument
909
+ /// is null the result will be null.
910
+ ///
911
+ /// \param[in] arg the value to extract sign from
912
+ /// \param[in] ctx the function execution context, optional
913
+ /// \return the element-wise sign function
914
+ ARROW_EXPORT
915
+ Result<Datum> Sign(const Datum& arg, ExecContext* ctx = NULLPTR);
916
+
917
+ /// \brief Round a value to a given precision.
918
+ ///
919
+ /// If arg is null the result will be null.
920
+ ///
921
+ /// \param[in] arg the value to be rounded
922
+ /// \param[in] options rounding options (rounding mode and number of digits), optional
923
+ /// \param[in] ctx the function execution context, optional
924
+ /// \return the element-wise rounded value
925
+ ARROW_EXPORT
926
+ Result<Datum> Round(const Datum& arg, RoundOptions options = RoundOptions::Defaults(),
927
+ ExecContext* ctx = NULLPTR);
928
+
929
+ /// \brief Round a value to a given precision.
930
+ ///
931
+ /// If arg1 is null the result will be null.
932
+ /// If arg2 is null then the result will be null. If arg2 is negative, then the rounding
933
+ /// place will be shifted to the left (thus -1 would correspond to rounding to the nearest
934
+ /// ten). If positive, the rounding place will shift to the right (and +1 would
935
+ /// correspond to rounding to the nearest tenth).
936
+ ///
937
+ /// \param[in] arg1 the value to be rounded
938
+ /// \param[in] arg2 the number of significant digits to round to
939
+ /// \param[in] options rounding options, optional
940
+ /// \param[in] ctx the function execution context, optional
941
+ /// \return the element-wise rounded value
942
+ ARROW_EXPORT
943
+ Result<Datum> RoundBinary(const Datum& arg1, const Datum& arg2,
944
+ RoundBinaryOptions options = RoundBinaryOptions::Defaults(),
945
+ ExecContext* ctx = NULLPTR);
946
+
947
+ /// \brief Round a value to a given multiple.
948
+ ///
949
+ /// If argument is null the result will be null.
950
+ ///
951
+ /// \param[in] arg the value to round
952
+ /// \param[in] options rounding options (rounding mode and multiple), optional
953
+ /// \param[in] ctx the function execution context, optional
954
+ /// \return the element-wise rounded value
955
+ ARROW_EXPORT
956
+ Result<Datum> RoundToMultiple(
957
+ const Datum& arg, RoundToMultipleOptions options = RoundToMultipleOptions::Defaults(),
958
+ ExecContext* ctx = NULLPTR);
959
+
960
+ /// \brief Ceil a temporal value to a given frequency
961
+ ///
962
+ /// If argument is null the result will be null.
963
+ ///
964
+ /// \param[in] arg the temporal value to ceil
965
+ /// \param[in] options temporal rounding options, optional
966
+ /// \param[in] ctx the function execution context, optional
967
+ /// \return the element-wise rounded value
968
+ ///
969
+ /// \since 7.0.0
970
+ /// \note API not yet finalized
971
+ ARROW_EXPORT
972
+ Result<Datum> CeilTemporal(
973
+ const Datum& arg, RoundTemporalOptions options = RoundTemporalOptions::Defaults(),
974
+ ExecContext* ctx = NULLPTR);
975
+
976
+ /// \brief Floor a temporal value to a given frequency
977
+ ///
978
+ /// If argument is null the result will be null.
979
+ ///
980
+ /// \param[in] arg the temporal value to floor
981
+ /// \param[in] options temporal rounding options, optional
982
+ /// \param[in] ctx the function execution context, optional
983
+ /// \return the element-wise rounded value
984
+ ///
985
+ /// \since 7.0.0
986
+ /// \note API not yet finalized
987
+ ARROW_EXPORT
988
+ Result<Datum> FloorTemporal(
989
+ const Datum& arg, RoundTemporalOptions options = RoundTemporalOptions::Defaults(),
990
+ ExecContext* ctx = NULLPTR);
991
+
992
+ /// \brief Round a temporal value to a given frequency
993
+ ///
994
+ /// If argument is null the result will be null.
995
+ ///
996
+ /// \param[in] arg the temporal value to round
997
+ /// \param[in] options temporal rounding options, optional
998
+ /// \param[in] ctx the function execution context, optional
999
+ /// \return the element-wise rounded value
1000
+ ///
1001
+ /// \since 7.0.0
1002
+ /// \note API not yet finalized
1003
+ ARROW_EXPORT
1004
+ Result<Datum> RoundTemporal(
1005
+ const Datum& arg, RoundTemporalOptions options = RoundTemporalOptions::Defaults(),
1006
+ ExecContext* ctx = NULLPTR);
1007
+
1008
+ /// \brief Invert the values of a boolean datum
1009
+ /// \param[in] value datum to invert
1010
+ /// \param[in] ctx the function execution context, optional
1011
+ /// \return the resulting datum
1012
+ ///
1013
+ /// \since 1.0.0
1014
+ /// \note API not yet finalized
1015
+ ARROW_EXPORT
1016
+ Result<Datum> Invert(const Datum& value, ExecContext* ctx = NULLPTR);
1017
+
1018
+ /// \brief Element-wise AND of two boolean datums which always propagates nulls
1019
+ /// (null and false is null).
1020
+ ///
1021
+ /// \param[in] left left operand
1022
+ /// \param[in] right right operand
1023
+ /// \param[in] ctx the function execution context, optional
1024
+ /// \return the resulting datum
1025
+ ///
1026
+ /// \since 1.0.0
1027
+ /// \note API not yet finalized
1028
+ ARROW_EXPORT
1029
+ Result<Datum> And(const Datum& left, const Datum& right, ExecContext* ctx = NULLPTR);
1030
+
1031
+ /// \brief Element-wise AND of two boolean datums with a Kleene truth table
1032
+ /// (null and false is false).
1033
+ ///
1034
+ /// \param[in] left left operand
1035
+ /// \param[in] right right operand
1036
+ /// \param[in] ctx the function execution context, optional
1037
+ /// \return the resulting datum
1038
+ ///
1039
+ /// \since 1.0.0
1040
+ /// \note API not yet finalized
1041
+ ARROW_EXPORT
1042
+ Result<Datum> KleeneAnd(const Datum& left, const Datum& right,
1043
+ ExecContext* ctx = NULLPTR);
1044
+
1045
+ /// \brief Element-wise OR of two boolean datums which always propagates nulls
1046
+ /// (null and true is null).
1047
+ ///
1048
+ /// \param[in] left left operand
1049
+ /// \param[in] right right operand
1050
+ /// \param[in] ctx the function execution context, optional
1051
+ /// \return the resulting datum
1052
+ ///
1053
+ /// \since 1.0.0
1054
+ /// \note API not yet finalized
1055
+ ARROW_EXPORT
1056
+ Result<Datum> Or(const Datum& left, const Datum& right, ExecContext* ctx = NULLPTR);
1057
+
1058
+ /// \brief Element-wise OR of two boolean datums with a Kleene truth table
1059
+ /// (null or true is true).
1060
+ ///
1061
+ /// \param[in] left left operand
1062
+ /// \param[in] right right operand
1063
+ /// \param[in] ctx the function execution context, optional
1064
+ /// \return the resulting datum
1065
+ ///
1066
+ /// \since 1.0.0
1067
+ /// \note API not yet finalized
1068
+ ARROW_EXPORT
1069
+ Result<Datum> KleeneOr(const Datum& left, const Datum& right, ExecContext* ctx = NULLPTR);
1070
+
1071
+ /// \brief Element-wise XOR of two boolean datums
1072
+ /// \param[in] left left operand
1073
+ /// \param[in] right right operand
1074
+ /// \param[in] ctx the function execution context, optional
1075
+ /// \return the resulting datum
1076
+ ///
1077
+ /// \since 1.0.0
1078
+ /// \note API not yet finalized
1079
+ ARROW_EXPORT
1080
+ Result<Datum> Xor(const Datum& left, const Datum& right, ExecContext* ctx = NULLPTR);
1081
+
1082
+ /// \brief Element-wise AND NOT of two boolean datums which always propagates nulls
1083
+ /// (null and not true is null).
1084
+ ///
1085
+ /// \param[in] left left operand
1086
+ /// \param[in] right right operand
1087
+ /// \param[in] ctx the function execution context, optional
1088
+ /// \return the resulting datum
1089
+ ///
1090
+ /// \since 3.0.0
1091
+ /// \note API not yet finalized
1092
+ ARROW_EXPORT
1093
+ Result<Datum> AndNot(const Datum& left, const Datum& right, ExecContext* ctx = NULLPTR);
1094
+
1095
+ /// \brief Element-wise AND NOT of two boolean datums with a Kleene truth table
1096
+ /// (false and not null is false, null and not true is false).
1097
+ ///
1098
+ /// \param[in] left left operand
1099
+ /// \param[in] right right operand
1100
+ /// \param[in] ctx the function execution context, optional
1101
+ /// \return the resulting datum
1102
+ ///
1103
+ /// \since 3.0.0
1104
+ /// \note API not yet finalized
1105
+ ARROW_EXPORT
1106
+ Result<Datum> KleeneAndNot(const Datum& left, const Datum& right,
1107
+ ExecContext* ctx = NULLPTR);
1108
+
1109
+ /// \brief IsIn returns true for each element of `values` that is contained in
1110
+ /// `value_set`
1111
+ ///
1112
+ /// Behaviour of nulls is governed by SetLookupOptions::skip_nulls.
1113
+ ///
1114
+ /// \param[in] values array-like input to look up in value_set
1115
+ /// \param[in] options SetLookupOptions
1116
+ /// \param[in] ctx the function execution context, optional
1117
+ /// \return the resulting datum
1118
+ ///
1119
+ /// \since 1.0.0
1120
+ /// \note API not yet finalized
1121
+ ARROW_EXPORT
1122
+ Result<Datum> IsIn(const Datum& values, const SetLookupOptions& options,
1123
+ ExecContext* ctx = NULLPTR);
1124
+ ARROW_EXPORT
1125
+ Result<Datum> IsIn(const Datum& values, const Datum& value_set,
1126
+ ExecContext* ctx = NULLPTR);
1127
+
1128
+ /// \brief IndexIn examines each slot in the values against a value_set array.
1129
+ /// If the value is not found in value_set, null will be output.
1130
+ /// If found, the index of occurrence within value_set (ignoring duplicates)
1131
+ /// will be output.
1132
+ ///
1133
+ /// For example given values = [99, 42, 3, null] and
1134
+ /// value_set = [3, 3, 99], the output will be = [2, null, 0, null]
1135
+ ///
1136
+ /// Behaviour of nulls is governed by SetLookupOptions::skip_nulls.
1137
+ ///
1138
+ /// \param[in] values array-like input
1139
+ /// \param[in] options SetLookupOptions
1140
+ /// \param[in] ctx the function execution context, optional
1141
+ /// \return the resulting datum
1142
+ ///
1143
+ /// \since 1.0.0
1144
+ /// \note API not yet finalized
1145
+ ARROW_EXPORT
1146
+ Result<Datum> IndexIn(const Datum& values, const SetLookupOptions& options,
1147
+ ExecContext* ctx = NULLPTR);
1148
+ ARROW_EXPORT
1149
+ Result<Datum> IndexIn(const Datum& values, const Datum& value_set,
1150
+ ExecContext* ctx = NULLPTR);
1151
+
1152
+ /// \brief IsValid returns true for each element of `values` that is not null,
1153
+ /// false otherwise
1154
+ ///
1155
+ /// \param[in] values input to examine for validity
1156
+ /// \param[in] ctx the function execution context, optional
1157
+ /// \return the resulting datum
1158
+ ///
1159
+ /// \since 1.0.0
1160
+ /// \note API not yet finalized
1161
+ ARROW_EXPORT
1162
+ Result<Datum> IsValid(const Datum& values, ExecContext* ctx = NULLPTR);
1163
+
1164
+ /// \brief IsNull returns true for each element of `values` that is null,
1165
+ /// false otherwise
1166
+ ///
1167
+ /// \param[in] values input to examine for nullity
1168
+ /// \param[in] options NullOptions
1169
+ /// \param[in] ctx the function execution context, optional
1170
+ /// \return the resulting datum
1171
+ ///
1172
+ /// \since 1.0.0
1173
+ /// \note API not yet finalized
1174
+ ARROW_EXPORT
1175
+ Result<Datum> IsNull(const Datum& values, NullOptions options = NullOptions::Defaults(),
1176
+ ExecContext* ctx = NULLPTR);
1177
+
1178
+ /// \brief IsNan returns true for each element of `values` that is NaN,
1179
+ /// false otherwise
1180
+ ///
1181
+ /// \param[in] values input to look for NaN
1182
+ /// \param[in] ctx the function execution context, optional
1183
+ /// \return the resulting datum
1184
+ ///
1185
+ /// \since 3.0.0
1186
+ /// \note API not yet finalized
1187
+ ARROW_EXPORT
1188
+ Result<Datum> IsNan(const Datum& values, ExecContext* ctx = NULLPTR);
1189
+
1190
+ /// \brief IfElse returns elements chosen from `left` or `right`
1191
+ /// depending on `cond`. `null` values in `cond` will be promoted to the result
1192
+ ///
1193
+ /// \param[in] cond `Boolean` condition Scalar/ Array
1194
+ /// \param[in] left Scalar/ Array
1195
+ /// \param[in] right Scalar/ Array
1196
+ /// \param[in] ctx the function execution context, optional
1197
+ ///
1198
+ /// \return the resulting datum
1199
+ ///
1200
+ /// \since 5.0.0
1201
+ /// \note API not yet finalized
1202
+ ARROW_EXPORT
1203
+ Result<Datum> IfElse(const Datum& cond, const Datum& left, const Datum& right,
1204
+ ExecContext* ctx = NULLPTR);
1205
+
1206
+ /// \brief CaseWhen behaves like a switch/case or if-else if-else statement: for
1207
+ /// each row, select the first value for which the corresponding condition is
1208
+ /// true, or (if given) select the 'else' value, else emit null. Note that a
1209
+ /// null condition is the same as false.
1210
+ ///
1211
+ /// \param[in] cond Conditions (Boolean)
1212
+ /// \param[in] cases Values (any type), along with an optional 'else' value.
1213
+ /// \param[in] ctx the function execution context, optional
1214
+ ///
1215
+ /// \return the resulting datum
1216
+ ///
1217
+ /// \since 5.0.0
1218
+ /// \note API not yet finalized
1219
+ ARROW_EXPORT
1220
+ Result<Datum> CaseWhen(const Datum& cond, const std::vector<Datum>& cases,
1221
+ ExecContext* ctx = NULLPTR);
1222
+
1223
+ /// \brief Year returns year for each element of `values`
1224
+ ///
1225
+ /// \param[in] values input to extract year from
1226
+ /// \param[in] ctx the function execution context, optional
1227
+ /// \return the resulting datum
1228
+ ///
1229
+ /// \since 5.0.0
1230
+ /// \note API not yet finalized
1231
+ ARROW_EXPORT
1232
+ Result<Datum> Year(const Datum& values, ExecContext* ctx = NULLPTR);
1233
+
1234
+ /// \brief IsLeapYear returns if a year is a leap year for each element of `values`
1235
+ ///
1236
+ /// \param[in] values input to extract leap year indicator from
1237
+ /// \param[in] ctx the function execution context, optional
1238
+ /// \return the resulting datum
1239
+ ///
1240
+ /// \since 8.0.0
1241
+ /// \note API not yet finalized
1242
+ ARROW_EXPORT
1243
+ Result<Datum> IsLeapYear(const Datum& values, ExecContext* ctx = NULLPTR);
1244
+
1245
+ /// \brief Month returns month for each element of `values`.
1246
+ /// Month is encoded as January=1, December=12
1247
+ ///
1248
+ /// \param[in] values input to extract month from
1249
+ /// \param[in] ctx the function execution context, optional
1250
+ /// \return the resulting datum
1251
+ ///
1252
+ /// \since 5.0.0
1253
+ /// \note API not yet finalized
1254
+ ARROW_EXPORT
1255
+ Result<Datum> Month(const Datum& values, ExecContext* ctx = NULLPTR);
1256
+
1257
+ /// \brief Day returns day number for each element of `values`
1258
+ ///
1259
+ /// \param[in] values input to extract day from
1260
+ /// \param[in] ctx the function execution context, optional
1261
+ /// \return the resulting datum
1262
+ ///
1263
+ /// \since 5.0.0
1264
+ /// \note API not yet finalized
1265
+ ARROW_EXPORT
1266
+ Result<Datum> Day(const Datum& values, ExecContext* ctx = NULLPTR);
1267
+
1268
+ /// \brief YearMonthDay returns a struct containing the Year, Month and Day value for
1269
+ /// each element of `values`.
1270
+ ///
1271
+ /// \param[in] values input to extract (year, month, day) struct from
1272
+ /// \param[in] ctx the function execution context, optional
1273
+ /// \return the resulting datum
1274
+ ///
1275
+ /// \since 7.0.0
1276
+ /// \note API not yet finalized
1277
+ ARROW_EXPORT
1278
+ Result<Datum> YearMonthDay(const Datum& values, ExecContext* ctx = NULLPTR);
1279
+
1280
+ /// \brief DayOfWeek returns number of the day of the week value for each element of
1281
+ /// `values`.
1282
+ ///
1283
+ /// By default week starts on Monday denoted by 0 and ends on Sunday denoted
1284
+ /// by 6. Start day of the week (Monday=1, Sunday=7) and numbering base (0 or 1) can be
1285
+ /// set using DayOfWeekOptions
1286
+ ///
1287
+ /// \param[in] values input to extract number of the day of the week from
1288
+ /// \param[in] options for setting start of the week and day numbering
1289
+ /// \param[in] ctx the function execution context, optional
1290
+ /// \return the resulting datum
1291
+ ///
1292
+ /// \since 5.0.0
1293
+ /// \note API not yet finalized
1294
+ ARROW_EXPORT Result<Datum> DayOfWeek(const Datum& values,
1295
+ DayOfWeekOptions options = DayOfWeekOptions(),
1296
+ ExecContext* ctx = NULLPTR);
1297
+
1298
+ /// \brief DayOfYear returns number of day of the year for each element of `values`.
1299
+ /// January 1st maps to day number 1, February 1st to 32, etc.
1300
+ ///
1301
+ /// \param[in] values input to extract number of day of the year from
1302
+ /// \param[in] ctx the function execution context, optional
1303
+ /// \return the resulting datum
1304
+ ///
1305
+ /// \since 5.0.0
1306
+ /// \note API not yet finalized
1307
+ ARROW_EXPORT Result<Datum> DayOfYear(const Datum& values, ExecContext* ctx = NULLPTR);
1308
+
1309
+ /// \brief ISOYear returns ISO year number for each element of `values`.
1310
+ /// First week of an ISO year has the majority (4 or more) of its days in January.
1311
+ ///
1312
+ /// \param[in] values input to extract ISO year from
1313
+ /// \param[in] ctx the function execution context, optional
1314
+ /// \return the resulting datum
1315
+ ///
1316
+ /// \since 5.0.0
1317
+ /// \note API not yet finalized
1318
+ ARROW_EXPORT
1319
+ Result<Datum> ISOYear(const Datum& values, ExecContext* ctx = NULLPTR);
1320
+
1321
+ /// \brief USYear returns US epidemiological year number for each element of `values`.
1322
+ /// First week of US epidemiological year has the majority (4 or more) of it's
1323
+ /// days in January. Last week of US epidemiological year has the year's last
1324
+ /// Wednesday in it. US epidemiological week starts on Sunday.
1325
+ ///
1326
+ /// \param[in] values input to extract US epidemiological year from
1327
+ /// \param[in] ctx the function execution context, optional
1328
+ /// \return the resulting datum
1329
+ ///
1330
+ /// \since 8.0.0
1331
+ /// \note API not yet finalized
1332
+ ARROW_EXPORT
1333
+ Result<Datum> USYear(const Datum& values, ExecContext* ctx = NULLPTR);
1334
+
1335
+ /// \brief ISOWeek returns ISO week of year number for each element of `values`.
1336
+ /// First ISO week has the majority (4 or more) of its days in January.
1337
+ /// ISO week starts on Monday. Year can have 52 or 53 weeks.
1338
+ /// Week numbering can start with 1.
1339
+ ///
1340
+ /// \param[in] values input to extract ISO week of year from
1341
+ /// \param[in] ctx the function execution context, optional
1342
+ /// \return the resulting datum
1343
+ ///
1344
+ /// \since 5.0.0
1345
+ /// \note API not yet finalized
1346
+ ARROW_EXPORT Result<Datum> ISOWeek(const Datum& values, ExecContext* ctx = NULLPTR);
1347
+
1348
+ /// \brief USWeek returns US week of year number for each element of `values`.
1349
+ /// First US week has the majority (4 or more) of its days in January.
1350
+ /// US week starts on Sunday. Year can have 52 or 53 weeks.
1351
+ /// Week numbering starts with 1.
1352
+ ///
1353
+ /// \param[in] values input to extract US week of year from
1354
+ /// \param[in] ctx the function execution context, optional
1355
+ /// \return the resulting datum
1356
+ ///
1357
+ /// \since 6.0.0
1358
+ /// \note API not yet finalized
1359
+ ARROW_EXPORT Result<Datum> USWeek(const Datum& values, ExecContext* ctx = NULLPTR);
1360
+
1361
+ /// \brief Week returns week of year number for each element of `values`.
1362
+ /// First ISO week has the majority (4 or more) of its days in January.
1363
+ /// Year can have 52 or 53 weeks. Week numbering can start with 0 or 1
1364
+ /// depending on DayOfWeekOptions.count_from_zero.
1365
+ ///
1366
+ /// \param[in] values input to extract week of year from
1367
+ /// \param[in] options for setting numbering start
1368
+ /// \param[in] ctx the function execution context, optional
1369
+ /// \return the resulting datum
1370
+ ///
1371
+ /// \since 6.0.0
1372
+ /// \note API not yet finalized
1373
+ ARROW_EXPORT Result<Datum> Week(const Datum& values, WeekOptions options = WeekOptions(),
1374
+ ExecContext* ctx = NULLPTR);
1375
+
1376
+ /// \brief ISOCalendar returns a (ISO year, ISO week, ISO day of week) struct for
1377
+ /// each element of `values`.
1378
+ /// ISO week starts on Monday denoted by 1 and ends on Sunday denoted by 7.
1379
+ ///
1380
+ /// \param[in] values input to ISO calendar struct from
1381
+ /// \param[in] ctx the function execution context, optional
1382
+ /// \return the resulting datum
1383
+ ///
1384
+ /// \since 5.0.0
1385
+ /// \note API not yet finalized
1386
+ ARROW_EXPORT Result<Datum> ISOCalendar(const Datum& values, ExecContext* ctx = NULLPTR);
1387
+
1388
+ /// \brief Quarter returns the quarter of year number for each element of `values`
1389
+ /// First quarter maps to 1 and fourth quarter maps to 4.
1390
+ ///
1391
+ /// \param[in] values input to extract quarter of year from
1392
+ /// \param[in] ctx the function execution context, optional
1393
+ /// \return the resulting datum
1394
+ ///
1395
+ /// \since 5.0.0
1396
+ /// \note API not yet finalized
1397
+ ARROW_EXPORT Result<Datum> Quarter(const Datum& values, ExecContext* ctx = NULLPTR);
1398
+
1399
+ /// \brief Hour returns hour value for each element of `values`
1400
+ ///
1401
+ /// \param[in] values input to extract hour from
1402
+ /// \param[in] ctx the function execution context, optional
1403
+ /// \return the resulting datum
1404
+ ///
1405
+ /// \since 5.0.0
1406
+ /// \note API not yet finalized
1407
+ ARROW_EXPORT
1408
+ Result<Datum> Hour(const Datum& values, ExecContext* ctx = NULLPTR);
1409
+
1410
+ /// \brief Minute returns minutes value for each element of `values`
1411
+ ///
1412
+ /// \param[in] values input to extract minutes from
1413
+ /// \param[in] ctx the function execution context, optional
1414
+ /// \return the resulting datum
1415
+ ///
1416
+ /// \since 5.0.0
1417
+ /// \note API not yet finalized
1418
+ ARROW_EXPORT
1419
+ Result<Datum> Minute(const Datum& values, ExecContext* ctx = NULLPTR);
1420
+
1421
+ /// \brief Second returns seconds value for each element of `values`
1422
+ ///
1423
+ /// \param[in] values input to extract seconds from
1424
+ /// \param[in] ctx the function execution context, optional
1425
+ /// \return the resulting datum
1426
+ ///
1427
+ /// \since 5.0.0
1428
+ /// \note API not yet finalized
1429
+ ARROW_EXPORT
1430
+ Result<Datum> Second(const Datum& values, ExecContext* ctx = NULLPTR);
1431
+
1432
+ /// \brief Millisecond returns number of milliseconds since the last full second
1433
+ /// for each element of `values`
1434
+ ///
1435
+ /// \param[in] values input to extract milliseconds from
1436
+ /// \param[in] ctx the function execution context, optional
1437
+ /// \return the resulting datum
1438
+ ///
1439
+ /// \since 5.0.0
1440
+ /// \note API not yet finalized
1441
+ ARROW_EXPORT
1442
+ Result<Datum> Millisecond(const Datum& values, ExecContext* ctx = NULLPTR);
1443
+
1444
+ /// \brief Microsecond returns number of microseconds since the last full millisecond
1445
+ /// for each element of `values`
1446
+ ///
1447
+ /// \param[in] values input to extract microseconds from
1448
+ /// \param[in] ctx the function execution context, optional
1449
+ /// \return the resulting datum
1450
+ ///
1451
+ /// \since 5.0.0
1452
+ /// \note API not yet finalized
1453
+ ARROW_EXPORT
1454
+ Result<Datum> Microsecond(const Datum& values, ExecContext* ctx = NULLPTR);
1455
+
1456
+ /// \brief Nanosecond returns number of nanoseconds since the last full millisecond
1457
+ /// for each element of `values`
1458
+ ///
1459
+ /// \param[in] values input to extract nanoseconds from
1460
+ /// \param[in] ctx the function execution context, optional
1461
+ /// \return the resulting datum
1462
+ ///
1463
+ /// \since 5.0.0
1464
+ /// \note API not yet finalized
1465
+ ARROW_EXPORT
1466
+ Result<Datum> Nanosecond(const Datum& values, ExecContext* ctx = NULLPTR);
1467
+
1468
+ /// \brief Subsecond returns the fraction of second elapsed since last full second
1469
+ /// as a float for each element of `values`
1470
+ ///
1471
+ /// \param[in] values input to extract subsecond from
1472
+ /// \param[in] ctx the function execution context, optional
1473
+ /// \return the resulting datum
1474
+ ///
1475
+ /// \since 5.0.0
1476
+ /// \note API not yet finalized
1477
+ ARROW_EXPORT Result<Datum> Subsecond(const Datum& values, ExecContext* ctx = NULLPTR);
1478
+
1479
+ /// \brief Format timestamps according to a format string
1480
+ ///
1481
+ /// Return formatted time strings according to the format string
1482
+ /// `StrftimeOptions::format` and to the locale specifier `Strftime::locale`.
1483
+ ///
1484
+ /// \param[in] values input timestamps
1485
+ /// \param[in] options for setting format string and locale
1486
+ /// \param[in] ctx the function execution context, optional
1487
+ /// \return the resulting datum
1488
+ ///
1489
+ /// \since 6.0.0
1490
+ /// \note API not yet finalized
1491
+ ARROW_EXPORT Result<Datum> Strftime(const Datum& values, StrftimeOptions options,
1492
+ ExecContext* ctx = NULLPTR);
1493
+
1494
+ /// \brief Parse timestamps according to a format string
1495
+ ///
1496
+ /// Return parsed timestamps according to the format string
1497
+ /// `StrptimeOptions::format` at time resolution `Strftime::unit`. Parse errors are
1498
+ /// raised depending on the `Strftime::error_is_null` setting.
1499
+ ///
1500
+ /// \param[in] values input strings
1501
+ /// \param[in] options for setting format string, unit and error_is_null
1502
+ /// \param[in] ctx the function execution context, optional
1503
+ /// \return the resulting datum
1504
+ ///
1505
+ /// \since 8.0.0
1506
+ /// \note API not yet finalized
1507
+ ARROW_EXPORT Result<Datum> Strptime(const Datum& values, StrptimeOptions options,
1508
+ ExecContext* ctx = NULLPTR);
1509
+
1510
+ /// \brief Converts timestamps from local timestamp without a timezone to a timestamp with
1511
+ /// timezone, interpreting the local timestamp as being in the specified timezone for each
1512
+ /// element of `values`
1513
+ ///
1514
+ /// \param[in] values input to convert
1515
+ /// \param[in] options for setting source timezone, exception and ambiguous timestamp
1516
+ /// handling.
1517
+ /// \param[in] ctx the function execution context, optional
1518
+ /// \return the resulting datum
1519
+ ///
1520
+ /// \since 6.0.0
1521
+ /// \note API not yet finalized
1522
+ ARROW_EXPORT Result<Datum> AssumeTimezone(const Datum& values,
1523
+ AssumeTimezoneOptions options,
1524
+ ExecContext* ctx = NULLPTR);
1525
+
1526
+ /// \brief IsDaylightSavings extracts if currently observing daylight savings for each
1527
+ /// element of `values`
1528
+ ///
1529
+ /// \param[in] values input to extract daylight savings indicator from
1530
+ /// \param[in] ctx the function execution context, optional
1531
+ /// \return the resulting datum
1532
+ ///
1533
+ /// \since 8.0.0
1534
+ /// \note API not yet finalized
1535
+ ARROW_EXPORT Result<Datum> IsDaylightSavings(const Datum& values,
1536
+ ExecContext* ctx = NULLPTR);
1537
+
1538
+ /// \brief LocalTimestamp converts timestamp to timezone naive local timestamp
1539
+ ///
1540
+ /// \param[in] values input to convert to local time
1541
+ /// \param[in] ctx the function execution context, optional
1542
+ /// \return the resulting datum
1543
+ ///
1544
+ /// \since 12.0.0
1545
+ /// \note API not yet finalized
1546
+ ARROW_EXPORT Result<Datum> LocalTimestamp(const Datum& values,
1547
+ ExecContext* ctx = NULLPTR);
1548
+
1549
+ /// \brief Years Between finds the number of years between two values
1550
+ ///
1551
+ /// \param[in] left input treated as the start time
1552
+ /// \param[in] right input treated as the end time
1553
+ /// \param[in] ctx the function execution context, optional
1554
+ /// \return the resulting datum
1555
+ ///
1556
+ /// \since 8.0.0
1557
+ /// \note API not yet finalized
1558
+ ARROW_EXPORT Result<Datum> YearsBetween(const Datum& left, const Datum& right,
1559
+ ExecContext* ctx = NULLPTR);
1560
+
1561
+ /// \brief Quarters Between finds the number of quarters between two values
1562
+ ///
1563
+ /// \param[in] left input treated as the start time
1564
+ /// \param[in] right input treated as the end time
1565
+ /// \param[in] ctx the function execution context, optional
1566
+ /// \return the resulting datum
1567
+ ///
1568
+ /// \since 8.0.0
1569
+ /// \note API not yet finalized
1570
+ ARROW_EXPORT Result<Datum> QuartersBetween(const Datum& left, const Datum& right,
1571
+ ExecContext* ctx = NULLPTR);
1572
+
1573
+ /// \brief Months Between finds the number of month between two values
1574
+ ///
1575
+ /// \param[in] left input treated as the start time
1576
+ /// \param[in] right input treated as the end time
1577
+ /// \param[in] ctx the function execution context, optional
1578
+ /// \return the resulting datum
1579
+ ///
1580
+ /// \since 8.0.0
1581
+ /// \note API not yet finalized
1582
+ ARROW_EXPORT Result<Datum> MonthsBetween(const Datum& left, const Datum& right,
1583
+ ExecContext* ctx = NULLPTR);
1584
+
1585
+ /// \brief Weeks Between finds the number of weeks between two values
1586
+ ///
1587
+ /// \param[in] left input treated as the start time
1588
+ /// \param[in] right input treated as the end time
1589
+ /// \param[in] ctx the function execution context, optional
1590
+ /// \return the resulting datum
1591
+ ///
1592
+ /// \since 8.0.0
1593
+ /// \note API not yet finalized
1594
+ ARROW_EXPORT Result<Datum> WeeksBetween(const Datum& left, const Datum& right,
1595
+ ExecContext* ctx = NULLPTR);
1596
+
1597
+ /// \brief Month Day Nano Between finds the number of months, days, and nanoseconds
1598
+ /// between two values
1599
+ ///
1600
+ /// \param[in] left input treated as the start time
1601
+ /// \param[in] right input treated as the end time
1602
+ /// \param[in] ctx the function execution context, optional
1603
+ /// \return the resulting datum
1604
+ ///
1605
+ /// \since 8.0.0
1606
+ /// \note API not yet finalized
1607
+ ARROW_EXPORT Result<Datum> MonthDayNanoBetween(const Datum& left, const Datum& right,
1608
+ ExecContext* ctx = NULLPTR);
1609
+
1610
+ /// \brief DayTime Between finds the number of days and milliseconds between two values
1611
+ ///
1612
+ /// \param[in] left input treated as the start time
1613
+ /// \param[in] right input treated as the end time
1614
+ /// \param[in] ctx the function execution context, optional
1615
+ /// \return the resulting datum
1616
+ ///
1617
+ /// \since 8.0.0
1618
+ /// \note API not yet finalized
1619
+ ARROW_EXPORT Result<Datum> DayTimeBetween(const Datum& left, const Datum& right,
1620
+ ExecContext* ctx = NULLPTR);
1621
+
1622
+ /// \brief Days Between finds the number of days between two values
1623
+ ///
1624
+ /// \param[in] left input treated as the start time
1625
+ /// \param[in] right input treated as the end time
1626
+ /// \param[in] ctx the function execution context, optional
1627
+ /// \return the resulting datum
1628
+ ///
1629
+ /// \since 8.0.0
1630
+ /// \note API not yet finalized
1631
+ ARROW_EXPORT Result<Datum> DaysBetween(const Datum& left, const Datum& right,
1632
+ ExecContext* ctx = NULLPTR);
1633
+
1634
+ /// \brief Hours Between finds the number of hours between two values
1635
+ ///
1636
+ /// \param[in] left input treated as the start time
1637
+ /// \param[in] right input treated as the end time
1638
+ /// \param[in] ctx the function execution context, optional
1639
+ /// \return the resulting datum
1640
+ ///
1641
+ /// \since 8.0.0
1642
+ /// \note API not yet finalized
1643
+ ARROW_EXPORT Result<Datum> HoursBetween(const Datum& left, const Datum& right,
1644
+ ExecContext* ctx = NULLPTR);
1645
+
1646
+ /// \brief Minutes Between finds the number of minutes between two values
1647
+ ///
1648
+ /// \param[in] left input treated as the start time
1649
+ /// \param[in] right input treated as the end time
1650
+ /// \param[in] ctx the function execution context, optional
1651
+ /// \return the resulting datum
1652
+ ///
1653
+ /// \since 8.0.0
1654
+ /// \note API not yet finalized
1655
+ ARROW_EXPORT Result<Datum> MinutesBetween(const Datum& left, const Datum& right,
1656
+ ExecContext* ctx = NULLPTR);
1657
+
1658
+ /// \brief Seconds Between finds the number of hours between two values
1659
+ ///
1660
+ /// \param[in] left input treated as the start time
1661
+ /// \param[in] right input treated as the end time
1662
+ /// \param[in] ctx the function execution context, optional
1663
+ /// \return the resulting datum
1664
+ ///
1665
+ /// \since 8.0.0
1666
+ /// \note API not yet finalized
1667
+ ARROW_EXPORT Result<Datum> SecondsBetween(const Datum& left, const Datum& right,
1668
+ ExecContext* ctx = NULLPTR);
1669
+
1670
+ /// \brief Milliseconds Between finds the number of milliseconds between two values
1671
+ ///
1672
+ /// \param[in] left input treated as the start time
1673
+ /// \param[in] right input treated as the end time
1674
+ /// \param[in] ctx the function execution context, optional
1675
+ /// \return the resulting datum
1676
+ ///
1677
+ /// \since 8.0.0
1678
+ /// \note API not yet finalized
1679
+ ARROW_EXPORT Result<Datum> MillisecondsBetween(const Datum& left, const Datum& right,
1680
+ ExecContext* ctx = NULLPTR);
1681
+
1682
+ /// \brief Microseconds Between finds the number of microseconds between two values
1683
+ ///
1684
+ /// \param[in] left input treated as the start time
1685
+ /// \param[in] right input treated as the end time
1686
+ /// \param[in] ctx the function execution context, optional
1687
+ /// \return the resulting datum
1688
+ ///
1689
+ /// \since 8.0.0
1690
+ /// \note API not yet finalized
1691
+ ARROW_EXPORT Result<Datum> MicrosecondsBetween(const Datum& left, const Datum& right,
1692
+ ExecContext* ctx = NULLPTR);
1693
+
1694
+ /// \brief Nanoseconds Between finds the number of nanoseconds between two values
1695
+ ///
1696
+ /// \param[in] left input treated as the start time
1697
+ /// \param[in] right input treated as the end time
1698
+ /// \param[in] ctx the function execution context, optional
1699
+ /// \return the resulting datum
1700
+ ///
1701
+ /// \since 8.0.0
1702
+ /// \note API not yet finalized
1703
+ ARROW_EXPORT Result<Datum> NanosecondsBetween(const Datum& left, const Datum& right,
1704
+ ExecContext* ctx = NULLPTR);
1705
+
1706
+ /// \brief Finds either the FIRST, LAST, or ALL items with a key that matches the given
1707
+ /// query key in a map.
1708
+ ///
1709
+ /// Returns an array of items for FIRST and LAST, and an array of list of items for ALL.
1710
+ ///
1711
+ /// \param[in] map to look in
1712
+ /// \param[in] options to pass a query key and choose which matching keys to return
1713
+ /// (FIRST, LAST or ALL)
1714
+ /// \param[in] ctx the function execution context, optional
1715
+ /// \return the resulting datum
1716
+ ///
1717
+ /// \since 8.0.0
1718
+ /// \note API not yet finalized
1719
+ ARROW_EXPORT Result<Datum> MapLookup(const Datum& map, MapLookupOptions options,
1720
+ ExecContext* ctx = NULLPTR);
1721
+ } // namespace compute
1722
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/compute/expression.h ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // This API is EXPERIMENTAL.
19
+
20
+ #pragma once
21
+
22
+ #include <memory>
23
+ #include <string>
24
+ #include <utility>
25
+ #include <variant>
26
+ #include <vector>
27
+
28
+ #include "arrow/compute/type_fwd.h"
29
+ #include "arrow/datum.h"
30
+ #include "arrow/type_fwd.h"
31
+ #include "arrow/util/small_vector.h"
32
+
33
+ namespace arrow {
34
+ namespace compute {
35
+
36
+ /// \defgroup expression-core Expressions to describe data transformations
37
+ ///
38
+ /// @{
39
+
40
+ /// An unbound expression which maps a single Datum to another Datum.
41
+ /// An expression is one of
42
+ /// - A literal Datum.
43
+ /// - A reference to a single (potentially nested) field of the input Datum.
44
+ /// - A call to a compute function, with arguments specified by other Expressions.
45
+ class ARROW_EXPORT Expression {
46
+ public:
47
+ struct Call {
48
+ std::string function_name;
49
+ std::vector<Expression> arguments;
50
+ std::shared_ptr<FunctionOptions> options;
51
+ // Cached hash value
52
+ size_t hash;
53
+
54
+ // post-Bind properties:
55
+ std::shared_ptr<Function> function;
56
+ const Kernel* kernel = NULLPTR;
57
+ std::shared_ptr<KernelState> kernel_state;
58
+ TypeHolder type;
59
+
60
+ void ComputeHash();
61
+ };
62
+
63
+ std::string ToString() const;
64
+ bool Equals(const Expression& other) const;
65
+ size_t hash() const;
66
+ struct Hash {
67
+ size_t operator()(const Expression& expr) const { return expr.hash(); }
68
+ };
69
+
70
+ /// Bind this expression to the given input type, looking up Kernels and field types.
71
+ /// Some expression simplification may be performed and implicit casts will be inserted.
72
+ /// Any state necessary for execution will be initialized and returned.
73
+ Result<Expression> Bind(const TypeHolder& in, ExecContext* = NULLPTR) const;
74
+ Result<Expression> Bind(const Schema& in_schema, ExecContext* = NULLPTR) const;
75
+
76
+ // XXX someday
77
+ // Clone all KernelState in this bound expression. If any function referenced by this
78
+ // expression has mutable KernelState, it is not safe to execute or apply simplification
79
+ // passes to it (or copies of it!) from multiple threads. Cloning state produces new
80
+ // KernelStates where necessary to ensure that Expressions may be manipulated safely
81
+ // on multiple threads.
82
+ // Result<ExpressionState> CloneState() const;
83
+ // Status SetState(ExpressionState);
84
+
85
+ /// Return true if all an expression's field references have explicit types
86
+ /// and all of its functions' kernels are looked up.
87
+ bool IsBound() const;
88
+
89
+ /// Return true if this expression is composed only of Scalar literals, field
90
+ /// references, and calls to ScalarFunctions.
91
+ bool IsScalarExpression() const;
92
+
93
+ /// Return true if this expression is literal and entirely null.
94
+ bool IsNullLiteral() const;
95
+
96
+ /// Return true if this expression could evaluate to true. Will return true for any
97
+ /// unbound or non-boolean Expressions. IsSatisfiable does not (currently) do any
98
+ /// canonicalization or simplification of the expression, so even Expressions
99
+ /// which are unsatisfiable may spuriously return `true` here. This function is
100
+ /// intended for use in predicate pushdown where a filter expression is simplified
101
+ /// by a guarantee, so it assumes that trying to simplify again would be redundant.
102
+ bool IsSatisfiable() const;
103
+
104
+ // XXX someday
105
+ // Result<PipelineGraph> GetPipelines();
106
+
107
+ bool is_valid() const { return impl_ != NULLPTR; }
108
+
109
+ /// Access a Call or return nullptr if this expression is not a call
110
+ const Call* call() const;
111
+ /// Access a Datum or return nullptr if this expression is not a literal
112
+ const Datum* literal() const;
113
+ /// Access a FieldRef or return nullptr if this expression is not a field_ref
114
+ const FieldRef* field_ref() const;
115
+
116
+ /// The type to which this expression will evaluate
117
+ const DataType* type() const;
118
+ // XXX someday
119
+ // NullGeneralization::type nullable() const;
120
+
121
+ struct Parameter {
122
+ FieldRef ref;
123
+
124
+ // post-bind properties
125
+ TypeHolder type;
126
+ ::arrow::internal::SmallVector<int, 2> indices;
127
+ };
128
+ const Parameter* parameter() const;
129
+
130
+ Expression() = default;
131
+ explicit Expression(Call call);
132
+ explicit Expression(Datum literal);
133
+ explicit Expression(Parameter parameter);
134
+
135
+ private:
136
+ using Impl = std::variant<Datum, Parameter, Call>;
137
+ std::shared_ptr<Impl> impl_;
138
+
139
+ ARROW_FRIEND_EXPORT friend bool Identical(const Expression& l, const Expression& r);
140
+ };
141
+
142
+ inline bool operator==(const Expression& l, const Expression& r) { return l.Equals(r); }
143
+ inline bool operator!=(const Expression& l, const Expression& r) { return !l.Equals(r); }
144
+
145
+ ARROW_EXPORT void PrintTo(const Expression&, std::ostream*);
146
+
147
+ // Factories
148
+
149
+ ARROW_EXPORT
150
+ Expression literal(Datum lit);
151
+
152
+ template <typename Arg>
153
+ Expression literal(Arg&& arg) {
154
+ return literal(Datum(std::forward<Arg>(arg)));
155
+ }
156
+
157
+ ARROW_EXPORT
158
+ Expression field_ref(FieldRef ref);
159
+
160
+ ARROW_EXPORT
161
+ Expression call(std::string function, std::vector<Expression> arguments,
162
+ std::shared_ptr<FunctionOptions> options = NULLPTR);
163
+
164
+ template <typename Options, typename = typename std::enable_if<
165
+ std::is_base_of<FunctionOptions, Options>::value>::type>
166
+ Expression call(std::string function, std::vector<Expression> arguments,
167
+ Options options) {
168
+ return call(std::move(function), std::move(arguments),
169
+ std::make_shared<Options>(std::move(options)));
170
+ }
171
+
172
+ /// Assemble a list of all fields referenced by an Expression at any depth.
173
+ ARROW_EXPORT
174
+ std::vector<FieldRef> FieldsInExpression(const Expression&);
175
+
176
+ /// Check if the expression references any fields.
177
+ ARROW_EXPORT
178
+ bool ExpressionHasFieldRefs(const Expression&);
179
+
180
+ struct ARROW_EXPORT KnownFieldValues;
181
+
182
+ /// Assemble a mapping from field references to known values. This derives known values
183
+ /// from "equal" and "is_null" Expressions referencing a field and a literal.
184
+ ARROW_EXPORT
185
+ Result<KnownFieldValues> ExtractKnownFieldValues(
186
+ const Expression& guaranteed_true_predicate);
187
+
188
+ /// @}
189
+
190
+ /// \defgroup expression-passes Functions for modification of Expressions
191
+ ///
192
+ /// @{
193
+ ///
194
+ /// These transform bound expressions. Some transforms utilize a guarantee, which is
195
+ /// provided as an Expression which is guaranteed to evaluate to true. The
196
+ /// guaranteed_true_predicate need not be bound, but canonicalization is currently
197
+ /// deferred to producers of guarantees. For example in order to be recognized as a
198
+ /// guarantee on a field value, an Expression must be a call to "equal" with field_ref LHS
199
+ /// and literal RHS. Flipping the arguments, "is_in" with a one-long value_set, ... or
200
+ /// other semantically identical Expressions will not be recognized.
201
+
202
+ /// Weak canonicalization which establishes guarantees for subsequent passes. Even
203
+ /// equivalent Expressions may result in different canonicalized expressions.
204
+ /// TODO this could be a strong canonicalization
205
+ ARROW_EXPORT
206
+ Result<Expression> Canonicalize(Expression, ExecContext* = NULLPTR);
207
+
208
+ /// Simplify Expressions based on literal arguments (for example, add(null, x) will always
209
+ /// be null so replace the call with a null literal). Includes early evaluation of all
210
+ /// calls whose arguments are entirely literal.
211
+ ARROW_EXPORT
212
+ Result<Expression> FoldConstants(Expression);
213
+
214
+ /// Simplify Expressions by replacing with known values of the fields which it references.
215
+ ARROW_EXPORT
216
+ Result<Expression> ReplaceFieldsWithKnownValues(const KnownFieldValues& known_values,
217
+ Expression);
218
+
219
+ /// Simplify an expression by replacing subexpressions based on a guarantee:
220
+ /// a boolean expression which is guaranteed to evaluate to `true`. For example, this is
221
+ /// used to remove redundant function calls from a filter expression or to replace a
222
+ /// reference to a constant-value field with a literal.
223
+ ARROW_EXPORT
224
+ Result<Expression> SimplifyWithGuarantee(Expression,
225
+ const Expression& guaranteed_true_predicate);
226
+
227
+ /// Replace all named field refs (e.g. "x" or "x.y") with field paths (e.g. [0] or [1,3])
228
+ ///
229
+ /// This isn't usually needed and does not offer any simplification by itself. However,
230
+ /// it can be useful to normalize an expression to paths to make it simpler to work with.
231
+ ARROW_EXPORT Result<Expression> RemoveNamedRefs(Expression expression);
232
+
233
+ /// @}
234
+
235
+ // Execution
236
+
237
+ /// Create an ExecBatch suitable for passing to ExecuteScalarExpression() from a
238
+ /// RecordBatch which may have missing or incorrectly ordered columns.
239
+ /// Missing fields will be replaced with null scalars.
240
+ ARROW_EXPORT Result<ExecBatch> MakeExecBatch(const Schema& full_schema,
241
+ const Datum& partial,
242
+ Expression guarantee = literal(true));
243
+
244
+ /// Execute a scalar expression against the provided state and input ExecBatch. This
245
+ /// expression must be bound.
246
+ ARROW_EXPORT
247
+ Result<Datum> ExecuteScalarExpression(const Expression&, const ExecBatch& input,
248
+ ExecContext* = NULLPTR);
249
+
250
+ /// Convenience function for invoking against a RecordBatch
251
+ ARROW_EXPORT
252
+ Result<Datum> ExecuteScalarExpression(const Expression&, const Schema& full_schema,
253
+ const Datum& partial_input, ExecContext* = NULLPTR);
254
+
255
+ // Serialization
256
+
257
+ ARROW_EXPORT
258
+ Result<std::shared_ptr<Buffer>> Serialize(const Expression&);
259
+
260
+ ARROW_EXPORT
261
+ Result<Expression> Deserialize(std::shared_ptr<Buffer>);
262
+
263
+ /// \defgroup expression-convenience Helpers for convenient expression creation
264
+ ///
265
+ /// @{
266
+
267
+ ARROW_EXPORT Expression project(std::vector<Expression> values,
268
+ std::vector<std::string> names);
269
+
270
+ ARROW_EXPORT Expression equal(Expression lhs, Expression rhs);
271
+
272
+ ARROW_EXPORT Expression not_equal(Expression lhs, Expression rhs);
273
+
274
+ ARROW_EXPORT Expression less(Expression lhs, Expression rhs);
275
+
276
+ ARROW_EXPORT Expression less_equal(Expression lhs, Expression rhs);
277
+
278
+ ARROW_EXPORT Expression greater(Expression lhs, Expression rhs);
279
+
280
+ ARROW_EXPORT Expression greater_equal(Expression lhs, Expression rhs);
281
+
282
+ ARROW_EXPORT Expression is_null(Expression lhs, bool nan_is_null = false);
283
+
284
+ ARROW_EXPORT Expression is_valid(Expression lhs);
285
+
286
+ ARROW_EXPORT Expression and_(Expression lhs, Expression rhs);
287
+ ARROW_EXPORT Expression and_(const std::vector<Expression>&);
288
+ ARROW_EXPORT Expression or_(Expression lhs, Expression rhs);
289
+ ARROW_EXPORT Expression or_(const std::vector<Expression>&);
290
+ ARROW_EXPORT Expression not_(Expression operand);
291
+
292
+ /// @}
293
+
294
+ } // namespace compute
295
+ } // namespace arrow