dataclass-native 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. dataclass_native/__init__.py +60 -0
  2. dataclass_native/__main__.py +5 -0
  3. dataclass_native/_arrow.py +822 -0
  4. dataclass_native/_json.py +783 -0
  5. dataclass_native/_mode.py +57 -0
  6. dataclass_native/_msgpack.py +207 -0
  7. dataclass_native/_native.py +234 -0
  8. dataclass_native/_runtime.py +607 -0
  9. dataclass_native/_version.py +24 -0
  10. dataclass_native/_wire.py +901 -0
  11. dataclass_native/arrays.py +13 -0
  12. dataclass_native/backends/__init__.py +0 -0
  13. dataclass_native/backends/bindings.py +74 -0
  14. dataclass_native/backends/cpp.py +574 -0
  15. dataclass_native/backends/templates/bindings.cpp.j2 +58 -0
  16. dataclass_native/backends/templates/extensions.cmake.j2 +12 -0
  17. dataclass_native/backends/templates/header.hpp.j2 +75 -0
  18. dataclass_native/cli.py +125 -0
  19. dataclass_native/cmake/dataclass_native-config.cmake +67 -0
  20. dataclass_native/include/dataclass_native/arrow.hpp +2022 -0
  21. dataclass_native/include/dataclass_native/json.hpp +1903 -0
  22. dataclass_native/include/dataclass_native/msgpack.hpp +1513 -0
  23. dataclass_native/include/dataclass_native/python.hpp +594 -0
  24. dataclass_native/include/dataclass_native/reflect.hpp +63 -0
  25. dataclass_native/include/dataclass_native/types.hpp +417 -0
  26. dataclass_native/introspect.py +811 -0
  27. dataclass_native/py.typed +0 -0
  28. dataclass_native/schema.py +553 -0
  29. dataclass_native/types.py +103 -0
  30. dataclass_native-1.0.0.dist-info/METADATA +339 -0
  31. dataclass_native-1.0.0.dist-info/RECORD +35 -0
  32. dataclass_native-1.0.0.dist-info/WHEEL +5 -0
  33. dataclass_native-1.0.0.dist-info/entry_points.txt +2 -0
  34. dataclass_native-1.0.0.dist-info/licenses/LICENSE +21 -0
  35. dataclass_native-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,13 @@
1
+ """
2
+ Annotations for fields which are numpy arrays, whose number of dimensions must be known:
3
+
4
+ - Vector[np.float64]: of one dimension
5
+ - Matrix[np.float64]: of two
6
+
7
+ Each is numpy's own annotation, as is that of an array of more: np.ndarray[tuple[int, int, int], np.dtype[np.float64]]
8
+ """
9
+
10
+ import numpy as np
11
+
12
+ type Vector[T: np.generic] = np.ndarray[tuple[int], np.dtype[T]]
13
+ type Matrix[T: np.generic] = np.ndarray[tuple[int, int], np.dtype[T]]
File without changes
@@ -0,0 +1,74 @@
1
+ """
2
+ Generates the source of a Python extension module per schema module, binding the C++ of dataclass_native.backends.cpp
3
+ with nanobind: the native classes which @native classes store their fields in.
4
+
5
+ - pkg/sub/mod.py -> pkg/sub/_mod_native.cpp, the extension module pkg.sub._mod_native
6
+ - extensions.cmake lists the extension modules, for dataclass_native_add_extensions
7
+ """
8
+
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from .. import schema as s
14
+ from .._native import extension_name
15
+ from .cpp import header_path, identifier, in_arrow, in_json, namespace, render
16
+
17
+ MANIFEST = "extensions.cmake"
18
+
19
+
20
+ def source_path(module: str) -> str:
21
+ return extension_name(module).replace(".", "/") + ".cpp"
22
+
23
+
24
+ def generate(schema: s.Schema) -> dict[str, str]:
25
+ """The source of each module's extension, and the manifest, by path relative to the output directory"""
26
+ files = {
27
+ source_path(name): generate_module(schema, name) for name in schema.modules
28
+ }
29
+ files[MANIFEST] = render(
30
+ MANIFEST + ".j2",
31
+ extensions=[extension_name(name) for name in schema.modules],
32
+ schemas=[
33
+ Path(file).as_posix()
34
+ for name in schema.modules
35
+ if (file := getattr(sys.modules[name], "__file__", None))
36
+ ],
37
+ )
38
+ return files
39
+
40
+
41
+ def generate_module(schema: s.Schema, module_name: str) -> str:
42
+ module = schema.modules[module_name]
43
+
44
+ def described(item: s.Struct | s.Enum) -> dict[str, Any]:
45
+ return {
46
+ "name": item.name,
47
+ "type": f"::{namespace(item.module)}::{identifier(item.name)}",
48
+ "hash": s.schema_hash(item),
49
+ }
50
+
51
+ def named(name: str) -> dict[str, str]:
52
+ return {"name": name, "identifier": identifier(name)}
53
+
54
+ return render(
55
+ "bindings.cpp.j2",
56
+ module=module.name,
57
+ extension=extension_name(module.name).rpartition(".")[2],
58
+ header=header_path(module.name),
59
+ dependencies=[extension_name(d) for d in module.dependencies],
60
+ enums=[
61
+ described(e) | {"members": [named(m.name) for m in e.members]}
62
+ for e in module.enums
63
+ ],
64
+ structs=[
65
+ described(st)
66
+ | {
67
+ "fields": [named(f.name) for f in st.fields],
68
+ "mutable": st.mutable,
69
+ "arrow": in_arrow(schema, st),
70
+ "json": in_json(schema, st.ref),
71
+ }
72
+ for st in module.structs
73
+ ],
74
+ )
@@ -0,0 +1,574 @@
1
+ """
2
+ Generates a C++ header per schema module: plain C++20 structs and enums, with no dependency on Python.
3
+
4
+ - pkg/sub/mod.py -> pkg/sub/mod.hpp, namespace pkg::sub::mod
5
+ - Each struct is an aggregate, with default member initialisers and a defaulted operator==
6
+ - Names which are C++ keywords have "_" appended
7
+ """
8
+
9
+ import datetime as dt
10
+ import math
11
+ from collections.abc import Iterator
12
+ from functools import cache
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from jinja2 import Environment, FileSystemLoader, StrictUndefined
17
+
18
+ from .. import schema as s
19
+ from ..schema import SchemaError
20
+
21
+ RUNTIME = "dataclass_native"
22
+ RUNTIME_HEADER = "dataclass_native/types.hpp"
23
+ REFLECT_HEADER = "dataclass_native/reflect.hpp"
24
+
25
+ # Including alternative tokens, and identifiers with special meaning
26
+ KEYWORDS = frozenset(
27
+ [
28
+ "alignas",
29
+ "alignof",
30
+ "and",
31
+ "and_eq",
32
+ "asm",
33
+ "auto",
34
+ "bitand",
35
+ "bitor",
36
+ "bool",
37
+ "break",
38
+ "case",
39
+ "catch",
40
+ "char",
41
+ "char8_t",
42
+ "char16_t",
43
+ "char32_t",
44
+ "class",
45
+ "compl",
46
+ "concept",
47
+ "const",
48
+ "consteval",
49
+ "constexpr",
50
+ "constinit",
51
+ "const_cast",
52
+ "continue",
53
+ "co_await",
54
+ "co_return",
55
+ "co_yield",
56
+ "decltype",
57
+ "default",
58
+ "delete",
59
+ "do",
60
+ "double",
61
+ "dynamic_cast",
62
+ "else",
63
+ "enum",
64
+ "explicit",
65
+ "export",
66
+ "extern",
67
+ "false",
68
+ "float",
69
+ "for",
70
+ "friend",
71
+ "goto",
72
+ "if",
73
+ "inline",
74
+ "int",
75
+ "long",
76
+ "mutable",
77
+ "namespace",
78
+ "new",
79
+ "noexcept",
80
+ "not",
81
+ "not_eq",
82
+ "nullptr",
83
+ "operator",
84
+ "or",
85
+ "or_eq",
86
+ "private",
87
+ "protected",
88
+ "public",
89
+ "register",
90
+ "reinterpret_cast",
91
+ "requires",
92
+ "return",
93
+ "short",
94
+ "signed",
95
+ "sizeof",
96
+ "static",
97
+ "static_assert",
98
+ "static_cast",
99
+ "struct",
100
+ "switch",
101
+ "template",
102
+ "this",
103
+ "thread_local",
104
+ "throw",
105
+ "true",
106
+ "try",
107
+ "typedef",
108
+ "typeid",
109
+ "typename",
110
+ "union",
111
+ "unsigned",
112
+ "using",
113
+ "virtual",
114
+ "void",
115
+ "volatile",
116
+ "wchar_t",
117
+ "while",
118
+ "xor",
119
+ "xor_eq",
120
+ "final",
121
+ "override",
122
+ "import",
123
+ "module",
124
+ ]
125
+ )
126
+
127
+ _EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.UTC)
128
+ _EPOCH_DATE = dt.date(1970, 1, 1)
129
+
130
+
131
+ def identifier(name: str) -> str:
132
+ if "__" in name or (name.startswith("_") and name[1:2].isupper()):
133
+ raise SchemaError(
134
+ f"{name!r} is reserved in C++: names may not contain '__', or start with '_' and a capital"
135
+ )
136
+ return f"{name}_" if name in KEYWORDS else name
137
+
138
+
139
+ def namespace(module: str) -> str:
140
+ return "::".join(identifier(part) for part in module.split("."))
141
+
142
+
143
+ def header_path(module: str) -> str:
144
+ return module.replace(".", "/") + ".hpp"
145
+
146
+
147
+ @cache
148
+ def _environment() -> Environment:
149
+ return Environment(
150
+ loader=FileSystemLoader(Path(__file__).parent / "templates"),
151
+ undefined=StrictUndefined,
152
+ trim_blocks=True,
153
+ lstrip_blocks=True,
154
+ keep_trailing_newline=True,
155
+ autoescape=False,
156
+ )
157
+
158
+
159
+ def render(template: str, **context: Any) -> str:
160
+ return _environment().get_template(template).render(context)
161
+
162
+
163
+ def generate(schema: s.Schema) -> dict[str, str]:
164
+ """The header for each module of the schema, by its path relative to the include directory"""
165
+ return {header_path(name): generate_module(schema, name) for name in schema.modules}
166
+
167
+
168
+ def generate_module(schema: s.Schema, module_name: str) -> str:
169
+ return _ModuleGenerator(schema, schema.modules[module_name]).generate()
170
+
171
+
172
+ class _ModuleGenerator:
173
+ def __init__(self, schema: s.Schema, module: s.Module):
174
+ self.__schema = schema
175
+ self.__module = module
176
+ self.__std_includes: set[str] = set()
177
+ self.__runtime = False
178
+
179
+ def generate(self) -> str:
180
+ module = self.__module
181
+ # Before the includes, which rendering them finds
182
+ enums = [self.__enum(e) for e in module.enums]
183
+ structs = [self.__struct(st) for st in module.structs]
184
+
185
+ includes = [f"<{h}>" for h in sorted(self.__std_includes)]
186
+ if enums or structs:
187
+ includes.append(f'"{REFLECT_HEADER}"')
188
+ if self.__runtime:
189
+ includes.append(f'"{RUNTIME_HEADER}"')
190
+ includes.extend(f'"{header_path(d)}"' for d in module.dependencies)
191
+
192
+ return render(
193
+ "header.hpp.j2",
194
+ module=module.name,
195
+ namespace=namespace(module.name),
196
+ includes=includes,
197
+ enums=enums,
198
+ forward_declarations=[identifier(st.name) for st in module.structs]
199
+ if self.__needs_forward_declarations()
200
+ else [],
201
+ structs=structs,
202
+ )
203
+
204
+ def __needs_forward_declarations(self) -> bool:
205
+ defined: set[str] = set()
206
+ for st in self.__module.structs:
207
+ for f in st.fields:
208
+ for t in _walk(f.type):
209
+ if (
210
+ isinstance(t, s.StructRef)
211
+ and t.module == st.module
212
+ and t.name not in defined
213
+ ):
214
+ return True
215
+ defined.add(st.name)
216
+ return False
217
+
218
+ def __enum(self, enum: s.Enum) -> dict[str, Any]:
219
+ values = [m.value for m in enum.members]
220
+ underlying = (
221
+ "std::int32_t"
222
+ if all(-(2**31) <= v < 2**31 for v in values)
223
+ else "std::int64_t"
224
+ )
225
+ self.__std_includes.add("cstdint")
226
+ return {
227
+ "name": identifier(enum.name),
228
+ "underlying": underlying,
229
+ "members": [
230
+ {
231
+ "name": identifier(m.name),
232
+ "value": _int(m.value, 64, True),
233
+ "literal": _literal(m.name),
234
+ "text": _literal(m.text),
235
+ "quoted": "true" if m.quoted else "false",
236
+ }
237
+ for m in enum.members
238
+ ],
239
+ **self.__described(enum),
240
+ }
241
+
242
+ def __struct(self, struct: s.Struct) -> dict[str, Any]:
243
+ shared = shared_structs(self.__schema, struct.ref, [], set())
244
+ members = []
245
+ for f in struct.fields:
246
+ where = f"{struct.cls.__qualname__}.{f.name}"
247
+ typ = self.type(f.type)
248
+ member = identifier(f.name)
249
+ if f.has_default:
250
+ members.append(
251
+ f"{typ} {member} = {self.value(f.type, f.default, where)};"
252
+ )
253
+ else:
254
+ members.append(f"{typ} {member}{{}};")
255
+
256
+ return {
257
+ "name": identifier(struct.name),
258
+ "members": members,
259
+ "shares": "true" if self.__shares(struct.ref, set()) else "false",
260
+ "shared": ", ".join(self.__qualified(ref) for ref in shared),
261
+ "arrow": "true" if in_arrow(self.__schema, struct) else "false",
262
+ "fields": [
263
+ {
264
+ "name": identifier(f.name),
265
+ "literal": _literal(f.name),
266
+ "has_default": "true" if f.has_default else "false",
267
+ }
268
+ for f in struct.fields
269
+ ],
270
+ **self.__described(struct),
271
+ }
272
+
273
+ @staticmethod
274
+ def __qualified(item: s.Struct | s.Enum | s.StructRef) -> str:
275
+ return f"::{namespace(item.module)}::{identifier(item.name)}"
276
+
277
+ def __described(self, item: s.Struct | s.Enum) -> dict[str, str]:
278
+ """What the item's reflection gives of it, besides its fields or members"""
279
+ return {
280
+ "qualified": self.__qualified(item),
281
+ "name_literal": _literal(item.name),
282
+ "tag_literal": _literal(item.tag),
283
+ }
284
+
285
+ def __shares(self, t: s.Type, seen: set[tuple[str, str]]) -> bool:
286
+ """Whether a value of the type may hold, however deeply, a Shared one"""
287
+ for inner in _walk(t):
288
+ if isinstance(inner, s.Shared):
289
+ return True
290
+ if (
291
+ isinstance(inner, s.StructRef)
292
+ and (inner.module, inner.name) not in seen
293
+ ):
294
+ seen.add((inner.module, inner.name))
295
+ if any(
296
+ self.__shares(f.type, seen)
297
+ for f in self.__schema.struct(inner).fields
298
+ ):
299
+ return True
300
+ return False
301
+
302
+ def __name(self, module: str, name: str) -> str:
303
+ if module == self.__module.name:
304
+ return identifier(name)
305
+ return f"::{namespace(module)}::{identifier(name)}"
306
+
307
+ def type(self, t: s.Type) -> str:
308
+ match t:
309
+ case s.Bool():
310
+ return "bool"
311
+ case s.Int(bits, signed):
312
+ self.__std_includes.add("cstdint")
313
+ return f"std::{'' if signed else 'u'}int{bits}_t"
314
+ case s.Float(bits):
315
+ return "float" if bits == 32 else "double"
316
+ case s.Str():
317
+ self.__std_includes.add("string")
318
+ return "std::string"
319
+ case (
320
+ s.Bytes()
321
+ | s.Date()
322
+ | s.Time()
323
+ | s.DateTime()
324
+ | s.NaiveDateTime()
325
+ | s.TimeDelta()
326
+ | s.Uuid()
327
+ ):
328
+ self.__runtime = True
329
+ name = "TimeOfDay" if isinstance(t, s.Time) else type(t).__name__
330
+ return f"{RUNTIME}::{name}"
331
+ case s.Decimal(places):
332
+ self.__runtime = True
333
+ return f"{RUNTIME}::Decimal<{places}>"
334
+ case s.StructRef(module, name, mutable=True):
335
+ self.__runtime = True
336
+ return f"{RUNTIME}::Mutable<{self.__name(module, name)}>"
337
+ case s.EnumRef(module, name) | s.StructRef(module, name):
338
+ return self.__name(module, name)
339
+ case s.Optional(inner):
340
+ self.__std_includes.add("optional")
341
+ return f"std::optional<{self.type(inner)}>"
342
+ case s.Sequence(element):
343
+ self.__std_includes.add("vector")
344
+ return f"std::vector<{self.type(element)}>"
345
+ case s.Array(element, dimensions):
346
+ self.__runtime = True
347
+ more = f", {dimensions}" if dimensions > 1 else ""
348
+ name = "MutableArray" if t.writeable else "Array"
349
+ return f"{RUNTIME}::{name}<{self.type(element)}{more}>"
350
+ case s.Tuple(elements):
351
+ self.__std_includes.add("tuple")
352
+ return f"std::tuple<{', '.join(self.type(e) for e in elements)}>"
353
+ case s.Set(element):
354
+ self.__std_includes.add("set")
355
+ return f"std::set<{self.type(element)}>"
356
+ case s.Map(key, value):
357
+ self.__std_includes.add("map")
358
+ return f"std::map<{self.type(key)}, {self.type(value)}>"
359
+ case s.Union(members, discriminated):
360
+ types = ", ".join(self.type(m) for m in members)
361
+ if discriminated:
362
+ self.__runtime = True
363
+ return f"{RUNTIME}::DiscriminatedUnion<{types}>"
364
+ self.__std_includes.add("variant")
365
+ return f"std::variant<{types}>"
366
+ case s.Shared(target):
367
+ self.__runtime = True
368
+ return f"{RUNTIME}::Shared<{self.type(target)}>"
369
+ case s.Indirect(target):
370
+ self.__runtime = True
371
+ return f"{RUNTIME}::Indirect<{self.type(target)}>"
372
+
373
+ def value(self, t: s.Type, v: Any, where: str) -> str:
374
+ """A C++ expression of type t, for the Python value v"""
375
+ match t:
376
+ case s.Bool():
377
+ return "true" if v else "false"
378
+ case s.Int(bits, signed):
379
+ return _int(v, bits, signed)
380
+ case s.Float(bits):
381
+ return self.__float(float(v), bits)
382
+ case s.Str():
383
+ return _string(v)
384
+ case s.Bytes():
385
+ return f"{self.type(t)}{{{', '.join(f'0x{b:02x}' for b in v)}}}"
386
+ case s.Date():
387
+ return (
388
+ f"{self.type(t)}{{std::chrono::days{{{(v - _EPOCH_DATE).days}}}}}"
389
+ )
390
+ case s.Time():
391
+ micros = (
392
+ (v.hour * 60 + v.minute) * 60 + v.second
393
+ ) * 1_000_000 + v.microsecond
394
+ return f"{self.type(t)}{{std::chrono::microseconds{{{micros}}}}}"
395
+ case s.DateTime():
396
+ micros = (v - _EPOCH) // dt.timedelta(microseconds=1)
397
+ return f"{self.type(t)}{{std::chrono::microseconds{{{micros}}}}}"
398
+ case s.NaiveDateTime():
399
+ micros = (v - _EPOCH.replace(tzinfo=None)) // dt.timedelta(
400
+ microseconds=1
401
+ )
402
+ return f"{self.type(t)}{{std::chrono::microseconds{{{micros}}}}}"
403
+ case s.TimeDelta():
404
+ return f"{self.type(t)}{{{v // dt.timedelta(microseconds=1)}}}"
405
+ case s.Decimal():
406
+ return f"{self.type(t)}{{{_int(t.unscaled(v), 64, True)}}}"
407
+ case s.Uuid():
408
+ return f"{self.type(t)}{{{{{{{', '.join(f'0x{b:02x}' for b in v.bytes)}}}}}}}"
409
+ case s.EnumRef():
410
+ return f"{self.type(t)}::{identifier(v.name)}"
411
+ case s.StructRef():
412
+ struct = self.__schema.struct(t)
413
+ inits = ", ".join(
414
+ f".{identifier(f.name)} = {self.value(f.type, getattr(v, f.name), where)}"
415
+ for f in struct.fields
416
+ )
417
+ made = f"{self.__name(t.module, t.name)}{{{inits}}}"
418
+ return f"{self.type(t)}{{{made}}}" if t.mutable else made
419
+ case s.Optional(inner):
420
+ if v is None:
421
+ self.__std_includes.add("optional")
422
+ return "std::nullopt"
423
+ return f"{self.type(t)}{{{self.value(inner, v, where)}}}"
424
+ case s.Sequence(element):
425
+ return f"{self.type(t)}{{{', '.join(self.value(element, e, where) for e in v)}}}"
426
+ case s.Array():
427
+ raise SchemaError(f"{where}: an array may not have a default")
428
+ case s.Tuple(elements):
429
+ values = ", ".join(
430
+ self.value(e, ev, where) for e, ev in zip(elements, v, strict=True)
431
+ )
432
+ return f"{self.type(t)}{{{values}}}"
433
+ case s.Set(element):
434
+ return f"{self.type(t)}{{{', '.join(sorted(self.value(element, e, where) for e in v))}}}"
435
+ case s.Map(key, value):
436
+ items = sorted(
437
+ f"{{{self.value(key, k, where)}, {self.value(value, kv, where)}}}"
438
+ for k, kv in v.items()
439
+ )
440
+ return f"{self.type(t)}{{{', '.join(items)}}}"
441
+ case s.Union():
442
+ index = s.union_member(t, v, self.__schema)
443
+ self.__std_includes.add("utility")
444
+ return f"{self.type(t)}{{std::in_place_index<{index}>, {self.value(t.members[index], v, where)}}}"
445
+ case s.Shared(target):
446
+ return f"{self.type(t)}{{{self.value(target, v, where)}}}"
447
+ case s.Indirect():
448
+ raise SchemaError(
449
+ f"{where}: in C++, a default may not hold a value of a recursive type"
450
+ )
451
+
452
+ def __float(self, v: float, bits: int) -> str:
453
+ typ = "float" if bits == 32 else "double"
454
+ if math.isnan(v) or math.isinf(v):
455
+ self.__std_includes.add("limits")
456
+ limit = "quiet_NaN" if math.isnan(v) else "infinity"
457
+ return f"{'-' if v < 0 else ''}std::numeric_limits<{typ}>::{limit}()"
458
+ literal = repr(v)
459
+ return f"{literal}f" if bits == 32 else literal
460
+
461
+
462
+ def shared_structs(
463
+ schema: s.Schema, t: s.Type, shared: list[s.StructRef], seen: set[s.StructRef]
464
+ ) -> list[s.StructRef]:
465
+ """The structs which a value of the type may share, however deeply, in the order met"""
466
+ for inner in _walk(t):
467
+ if isinstance(inner, s.Shared) and inner.target not in shared:
468
+ shared.append(inner.target)
469
+ if isinstance(inner, s.StructRef) and inner not in seen:
470
+ seen.add(inner)
471
+ for f in schema.struct(inner).fields:
472
+ shared_structs(schema, f.type, shared, seen)
473
+ return shared
474
+
475
+
476
+ def in_json(schema: s.Schema, t: s.Type, seen: set[s.StructRef] | None = None) -> bool:
477
+ """Whether a value of a type may be written as JSON: not if a union it may hold has members which cannot be told
478
+ apart in it"""
479
+ seen = set() if seen is None else seen
480
+ match t:
481
+ case s.StructRef() | s.Shared(target=s.StructRef()) | s.Indirect():
482
+ ref = t if isinstance(t, s.StructRef) else t.target
483
+ if ref in seen:
484
+ return True
485
+ seen.add(ref)
486
+ return all(in_json(schema, f.type, seen) for f in schema.struct(ref).fields)
487
+ case s.Optional(inner) | s.Sequence(inner) | s.Set(inner) | s.Map(_, inner):
488
+ return in_json(schema, inner, seen)
489
+ case s.Tuple(members):
490
+ return all(in_json(schema, m, seen) for m in members)
491
+ case s.Union(members):
492
+ return s.json_collision(t) is None and all(
493
+ in_json(schema, m, seen) for m in members
494
+ )
495
+ case _:
496
+ return True
497
+
498
+
499
+ def in_arrow(schema: s.Schema, struct: s.Struct) -> bool:
500
+ """Whether a struct may be held in Arrow tables: not if it, or a struct it may share, holds itself"""
501
+ shared = shared_structs(schema, struct.ref, [], set())
502
+ return not any(_holds_itself(schema, ref, ()) for ref in (struct.ref, *shared))
503
+
504
+
505
+ def _holds_itself(schema: s.Schema, t: s.Type, within: tuple[s.StructRef, ...]) -> bool:
506
+ """Whether a value of the type may hold, other than as a Shared value, one of a struct it is within"""
507
+ match t:
508
+ case s.StructRef():
509
+ return t in within or any(
510
+ _holds_itself(schema, f.type, (*within, t))
511
+ for f in schema.struct(t).fields
512
+ )
513
+ case s.Indirect(target):
514
+ return _holds_itself(schema, target, within)
515
+ case s.Optional(inner) | s.Sequence(inner) | s.Map(_, inner):
516
+ return _holds_itself(schema, inner, within)
517
+ case s.Tuple(members) | s.Union(members):
518
+ return any(_holds_itself(schema, m, within) for m in members)
519
+ case _:
520
+ return False
521
+
522
+
523
+ def _walk(t: s.Type) -> Iterator[s.Type]:
524
+ yield t
525
+ match t:
526
+ case s.Optional(inner):
527
+ yield from _walk(inner)
528
+ case s.Sequence(element) | s.Set(element):
529
+ yield from _walk(element)
530
+ case s.Tuple(members) | s.Union(members):
531
+ for member in members:
532
+ yield from _walk(member)
533
+ case s.Map(key, value):
534
+ yield from _walk(key)
535
+ yield from _walk(value)
536
+ case s.Shared(target) | s.Indirect(target):
537
+ yield target
538
+ case _:
539
+ pass
540
+
541
+
542
+ def _int(v: int, bits: int, signed: bool) -> str:
543
+ if not signed:
544
+ return f"{v}ULL"
545
+ if v == -(2**63):
546
+ # As 9223372036854775808 is not a valid literal
547
+ return "(-9223372036854775807LL - 1)"
548
+ return f"{v}LL" if bits == 64 and not -(2**31) <= v < 2**31 else str(v)
549
+
550
+
551
+ def _literal(v: str) -> str:
552
+ """A string literal, escaping all but printable ASCII as octal, which unlike hex escapes cannot run on"""
553
+ data = v.encode()
554
+ chars = []
555
+ for b in data:
556
+ c = chr(b)
557
+ if c in '"\\':
558
+ chars.append("\\" + c)
559
+ elif 0x20 <= b < 0x7F:
560
+ chars.append(c)
561
+ else:
562
+ chars.append(f"\\{b:03o}")
563
+ return f'"{"".join(chars)}"'
564
+
565
+
566
+ def _string(v: str) -> str:
567
+ """A std::string"""
568
+ data, literal = v.encode(), _literal(v)
569
+ # With an embedded NUL, the length must be given
570
+ return (
571
+ f"std::string({literal}, {len(data)})"
572
+ if b"\0" in data
573
+ else f"std::string{{{literal}}}"
574
+ )