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,811 @@
1
+ """
2
+ Builds the schema model from the @native dataclasses of some modules, and of the modules they use.
3
+
4
+ A module's schema holds all its @native classes, and all the enums it defines. Run in pure mode, as default factories
5
+ of @native classes are called, which in strict mode needs the binding being generated.
6
+ """
7
+
8
+ import datetime as dt
9
+ import decimal
10
+ import sys
11
+ import typing
12
+ import uuid
13
+ from collections import abc
14
+ from collections.abc import Iterable, Iterator
15
+ from dataclasses import MISSING, Field, fields, is_dataclass, replace
16
+ from enum import Enum, Flag
17
+ from importlib import import_module
18
+ from types import ModuleType, NoneType, UnionType
19
+ from typing import Annotated, Any, get_args, get_origin, get_type_hints
20
+
21
+ from . import schema as s
22
+ from ._native import _registry, is_native, native_info
23
+ from .schema import SchemaError
24
+ from .types import (
25
+ DiscriminatedMarker,
26
+ FloatSpec,
27
+ IntSpec,
28
+ NaiveMarker,
29
+ SharedMarker,
30
+ )
31
+
32
+ _SCALARS: dict[type, s.Type] = {
33
+ bool: s.Bool(),
34
+ int: s.Int(),
35
+ float: s.Float(),
36
+ str: s.Str(),
37
+ bytes: s.Bytes(),
38
+ dt.date: s.Date(),
39
+ dt.time: s.Time(),
40
+ dt.datetime: s.DateTime(),
41
+ dt.timedelta: s.TimeDelta(),
42
+ uuid.UUID: s.Uuid(),
43
+ }
44
+
45
+ # Containers which are, or may be, mutable: unsupported, with the immutable type to use instead
46
+ _ALTERNATIVES: dict[Any, str] = {
47
+ list: "tuple[T, ...]",
48
+ abc.Sequence: "tuple[T, ...]",
49
+ abc.MutableSequence: "tuple[T, ...]",
50
+ set: "frozenset[T]",
51
+ abc.Set: "frozenset[T]",
52
+ abc.MutableSet: "frozenset[T]",
53
+ dict: "Mapping[K, V]",
54
+ abc.MutableMapping: "Mapping[K, V]",
55
+ }
56
+
57
+ # Containers which must be parameterised, with an example
58
+ _PARAMETERISED: dict[type, str] = {
59
+ tuple: "tuple[int, ...]",
60
+ frozenset: "frozenset[int]",
61
+ abc.Mapping: "Mapping[str, int]",
62
+ }
63
+
64
+
65
+ def build_schema(modules: Iterable[str | ModuleType]) -> s.Schema:
66
+ """The schema of the given modules, and of those whose types they use"""
67
+ return _Builder().build(modules)
68
+
69
+
70
+ def describe(cls: type) -> s.Struct | s.Enum:
71
+ """
72
+ A @native class or an enum, alone. As the rest of its module is not considered, a struct's recursive references
73
+ are not Indirect, and it has no defaults
74
+ """
75
+ return _Builder().describe(cls)
76
+
77
+
78
+ def resolve(tp: Any, where: str) -> s.Type:
79
+ """The schema type of a type annotation, alone, as describe: where names it, in an error"""
80
+ return _Builder().resolve(tp, where)
81
+
82
+
83
+ def _module_name(module: str | ModuleType) -> str:
84
+ return module.__name__ if isinstance(module, ModuleType) else module
85
+
86
+
87
+ def _check_top_level(cls: type):
88
+ if cls.__qualname__ != cls.__name__:
89
+ raise SchemaError(
90
+ f"{cls.__qualname__}: nested and local classes are not supported in the schema"
91
+ )
92
+
93
+
94
+ class _RawStruct:
95
+ def __init__(self, cls: type, fields_: list[tuple[str, s.Type, Field]]):
96
+ self.cls = cls
97
+ self.fields = fields_
98
+
99
+
100
+ class _Builder:
101
+ def __init__(self):
102
+ self.__structs: dict[type, _RawStruct] = {}
103
+ self.__enums: dict[type, s.Enum] = {}
104
+ self.__modules: list[str] = []
105
+ self.__queue: list[str] = []
106
+
107
+ def build(self, modules: Iterable[str | ModuleType]) -> s.Schema:
108
+ for module in modules:
109
+ self.__use_module(_module_name(module))
110
+
111
+ while self.__queue:
112
+ self.__add_module(self.__queue.pop(0))
113
+
114
+ self.__check_tags()
115
+ recursive = self.__recursive_cycles()
116
+ structs = {
117
+ cls: self.__struct(raw, recursive.get(cls, frozenset()))
118
+ for cls, raw in self.__structs.items()
119
+ }
120
+
121
+ modules_ = {}
122
+ for name in self.__modules:
123
+ module_structs = [st for st in structs.values() if st.module == name]
124
+ modules_[name] = s.Module(
125
+ name=name,
126
+ enums=tuple(e for e in self.__enums.values() if e.module == name),
127
+ structs=_ordered(module_structs),
128
+ dependencies=_dependencies(name, module_structs),
129
+ )
130
+
131
+ _check_module_cycles(modules_)
132
+ schema = s.Schema(modules_)
133
+ _check_defaults(schema)
134
+ return schema
135
+
136
+ def describe(self, cls: type) -> s.Struct | s.Enum:
137
+ _check_top_level(cls)
138
+ if issubclass(cls, Enum):
139
+ self.__add_enum(cls)
140
+ return self.__enums[cls]
141
+
142
+ self.__add_struct(cls)
143
+ return s.Struct(
144
+ module=cls.__module__,
145
+ name=cls.__name__,
146
+ tag=native_info(cls).tag,
147
+ fields=tuple(s.Field(name, t) for name, t, _ in self.__structs[cls].fields),
148
+ cls=cls,
149
+ mutable=not cls.__dataclass_params__.frozen,
150
+ )
151
+
152
+ def resolve(self, tp: Any, where: str) -> s.Type:
153
+ return _arrays_alone(self.__resolve(tp, where), where)
154
+
155
+ def __use_module(self, name: str):
156
+ if name not in self.__modules:
157
+ self.__modules.append(name)
158
+ self.__queue.append(name)
159
+
160
+ def __add_module(self, name: str):
161
+ module = import_module(name)
162
+ for cls in [c for c in list(_registry) if c.__module__ == name]:
163
+ # Ignoring classes since redefined, e.g. on reloading
164
+ if (
165
+ vars(module).get(cls.__name__) is cls
166
+ or cls.__qualname__ != cls.__name__
167
+ ):
168
+ _check_top_level(cls)
169
+ self.__add_struct(cls)
170
+
171
+ for value in list(vars(module).values()):
172
+ if (
173
+ isinstance(value, type)
174
+ and issubclass(value, Enum)
175
+ and not issubclass(value, Flag)
176
+ and value.__module__ == name
177
+ and value.__qualname__ == value.__name__
178
+ ):
179
+ self.__add_enum(value)
180
+
181
+ def __add_struct(self, cls: type):
182
+ if cls in self.__structs:
183
+ return
184
+
185
+ try:
186
+ hints = get_type_hints(cls, include_extras=True)
187
+ except Exception as e:
188
+ raise SchemaError(
189
+ f"{cls.__qualname__}: cannot resolve its type annotations: {e}"
190
+ ) from e
191
+
192
+ resolved = []
193
+ for f in fields(cls):
194
+ where = f"{cls.__qualname__}.{f.name}"
195
+ t = self.resolve(hints[f.name], where)
196
+ if not cls.__dataclass_params__.frozen: # pyright: ignore[reportAttributeAccessIssue]
197
+ t = _written(t)
198
+ resolved.append((f.name, t, f))
199
+
200
+ self.__structs[cls] = _RawStruct(cls, resolved)
201
+
202
+ def __add_enum(self, cls: type[Enum]):
203
+ if cls in self.__enums:
204
+ return
205
+
206
+ members = tuple(cls)
207
+ if not members:
208
+ raise SchemaError(f"{cls.__qualname__}: enums must have members")
209
+
210
+ int_values = all(
211
+ type(m.value) is int and -(2**63) <= m.value < 2**63 for m in members
212
+ )
213
+ by_value = s.json_values(cls) is not None
214
+ self.__enums[cls] = s.Enum(
215
+ module=cls.__module__,
216
+ name=cls.__name__,
217
+ tag=f"{cls.__module__}.{cls.__qualname__}",
218
+ members=tuple(
219
+ s.EnumMember(
220
+ m.name,
221
+ m.value if int_values else i,
222
+ str(m.value) if by_value else m.name,
223
+ not by_value or type(m.value) is str,
224
+ )
225
+ for i, m in enumerate(members)
226
+ ),
227
+ cls=cls,
228
+ )
229
+
230
+ def __resolve(
231
+ self, tp: Any, where: str, shared: bool = False, discriminated: bool = False
232
+ ) -> s.Type:
233
+ origin = get_origin(tp)
234
+
235
+ if origin is Annotated:
236
+ base, *metadata = get_args(tp)
237
+ shared = shared or any(isinstance(m, SharedMarker) for m in metadata)
238
+ discriminated = any(isinstance(m, DiscriminatedMarker) for m in metadata)
239
+ resolved = (
240
+ _decimal(metadata, where)
241
+ if base is decimal.Decimal
242
+ else self.__resolve(base, where, shared, discriminated)
243
+ )
244
+
245
+ for m in metadata:
246
+ if isinstance(m, IntSpec):
247
+ if not isinstance(resolved, s.Int) or m.bits not in (8, 16, 32, 64):
248
+ raise SchemaError(
249
+ f"{where}: {m} applies only to int, with 8, 16, 32 or 64 bits"
250
+ )
251
+ resolved = s.Int(m.bits, m.signed)
252
+ elif isinstance(m, FloatSpec):
253
+ if not isinstance(resolved, s.Float) or m.bits not in (32, 64):
254
+ raise SchemaError(
255
+ f"{where}: {m} applies only to float, with 32 or 64 bits"
256
+ )
257
+ resolved = s.Float(m.bits)
258
+ elif isinstance(m, NaiveMarker):
259
+ if not isinstance(resolved, s.DateTime):
260
+ raise SchemaError(f"{where}: {m} applies only to datetime")
261
+ resolved = s.NaiveDateTime()
262
+
263
+ return resolved
264
+
265
+ if isinstance(tp, typing.TypeAliasType):
266
+ return self.__resolve(tp.__value__, where, shared, discriminated)
267
+
268
+ if isinstance(origin, typing.TypeAliasType):
269
+ # An alias with parameters, as numpy's NDArray is
270
+ return self.__resolve(
271
+ origin.__value__[get_args(tp)], where, shared, discriminated
272
+ )
273
+
274
+ if isinstance(tp, typing.NewType):
275
+ return self.__resolve(tp.__supertype__, where, shared, discriminated)
276
+
277
+ if origin in (typing.Union, UnionType):
278
+ return self.__union(get_args(tp), where, shared, discriminated)
279
+
280
+ if discriminated:
281
+ raise SchemaError(f"{where}: DiscriminatedUnion needs at least two types")
282
+
283
+ if isinstance(tp, type) and origin is None:
284
+ return self.__resolve_class(tp, where, shared)
285
+
286
+ if shared:
287
+ raise SchemaError(
288
+ f"{where}: Shared applies only to @native classes, or unions of them"
289
+ )
290
+
291
+ args = get_args(tp)
292
+ if (np := sys.modules.get("numpy")) and origin is np.ndarray:
293
+ return _array(np, tp, where)
294
+
295
+ if origin is tuple:
296
+ if len(args) == 2 and args[1] is Ellipsis:
297
+ return s.Sequence(self.__resolve(args[0], where))
298
+ if not args or Ellipsis in args:
299
+ raise SchemaError(
300
+ f"{where}: unsupported tuple type {tp}: use tuple[T, ...] or tuple[A, B, ...]"
301
+ )
302
+ return s.Tuple(tuple(self.__resolve(a, where) for a in args))
303
+
304
+ if origin is frozenset:
305
+ return s.Set(self.__key(args[0], where))
306
+
307
+ if origin is abc.Mapping:
308
+ return s.Map(self.__key(args[0], where), self.__resolve(args[1], where))
309
+
310
+ if origin in _ALTERNATIVES:
311
+ raise SchemaError(
312
+ f"{where}: {tp} is not supported, as only immutable types are: use {_ALTERNATIVES[origin]}"
313
+ )
314
+
315
+ raise SchemaError(f"{where}: unsupported type {tp}")
316
+
317
+ def __resolve_class(self, tp: type, where: str, shared: bool) -> s.Type:
318
+ if tp is NoneType:
319
+ raise SchemaError(f"{where}: None alone is not a supported type")
320
+
321
+ if is_dataclass(tp):
322
+ if not is_native(tp):
323
+ raise SchemaError(
324
+ f"{where}: dataclass {tp.__qualname__} must be decorated with @native"
325
+ )
326
+ _check_top_level(tp)
327
+ self.__use_module(tp.__module__)
328
+ mutable = not tp.__dataclass_params__.frozen # pyright: ignore[reportAttributeAccessIssue]
329
+ if shared and mutable:
330
+ raise SchemaError(
331
+ f"{where}: Shared applies only to frozen classes: {tp.__qualname__} is not, so is held by "
332
+ "reference as it is"
333
+ )
334
+ ref = s.StructRef(tp.__module__, tp.__name__, tp, mutable)
335
+ return s.Shared(ref) if shared else ref
336
+
337
+ if shared:
338
+ raise SchemaError(
339
+ f"{where}: Shared applies only to @native classes, or unions of them, not {tp}"
340
+ )
341
+
342
+ if tp in _SCALARS:
343
+ return _SCALARS[tp]
344
+ if tp is decimal.Decimal:
345
+ return _decimal((), where)
346
+ if pydantic := sys.modules.get("pydantic"):
347
+ # Which say whether a datetime has a timezone, as ours do
348
+ if tp is pydantic.NaiveDatetime:
349
+ return s.NaiveDateTime()
350
+ if tp is pydantic.AwareDatetime:
351
+ return s.DateTime()
352
+
353
+ if issubclass(tp, Enum):
354
+ if issubclass(tp, Flag):
355
+ raise SchemaError(f"{where}: Flag enums are not supported")
356
+ _check_top_level(tp)
357
+ self.__use_module(tp.__module__)
358
+ return s.EnumRef(tp.__module__, tp.__name__, tp)
359
+
360
+ if tp in _PARAMETERISED:
361
+ raise SchemaError(
362
+ f"{where}: {tp.__name__} must be parameterised, e.g. {_PARAMETERISED[tp]}"
363
+ )
364
+
365
+ if tp in _ALTERNATIVES:
366
+ raise SchemaError(
367
+ f"{where}: {tp.__name__} is not supported, as only immutable types are: use {_ALTERNATIVES[tp]}"
368
+ )
369
+
370
+ raise SchemaError(f"{where}: unsupported type {tp.__qualname__}")
371
+
372
+ def __key(self, tp: Any, where: str) -> s.Type:
373
+ key = self.__resolve(tp, where)
374
+ if not s.is_key(key):
375
+ raise SchemaError(
376
+ f"{where}: frozenset elements and Mapping keys must be scalars or enums, not {tp}"
377
+ )
378
+ return key
379
+
380
+ def __union(
381
+ self, args: tuple[Any, ...], where: str, shared: bool, discriminated: bool
382
+ ) -> s.Type:
383
+ if discriminated and NoneType in args:
384
+ raise SchemaError(
385
+ f"{where}: DiscriminatedUnion cannot include None: use DiscriminatedUnion[...] | None"
386
+ )
387
+
388
+ optional = NoneType in args
389
+ others = len(args) - optional > 1
390
+ members: list[s.Type] = []
391
+ for arg in (a for a in args if a is not NoneType):
392
+ member = self.__resolve(arg, where, shared)
393
+ if isinstance(member, s.Optional):
394
+ optional = True
395
+ member = member.inner
396
+
397
+ if isinstance(member, s.Union) and others:
398
+ if member.discriminated:
399
+ raise SchemaError(
400
+ f"{where}: include all the members of a union in its DiscriminatedUnion"
401
+ )
402
+ members.extend(member.members)
403
+ else:
404
+ members.append(member)
405
+
406
+ members = list(dict.fromkeys(members))
407
+ if not members:
408
+ raise SchemaError(f"{where}: None alone is not a supported type")
409
+ if len(members) > 1 and any(isinstance(m, s.Array) for m in members):
410
+ raise SchemaError(f"{where}: {_ARRAY_ALONE}")
411
+
412
+ if len(members) == 1:
413
+ inner = members[0]
414
+ else:
415
+ inner = s.Union(tuple(members), discriminated)
416
+ self.__check_union(inner, where)
417
+
418
+ return s.Optional(inner) if optional else inner
419
+
420
+ def __check_union(self, union: s.Union, where: str):
421
+ if union.discriminated:
422
+ tags: dict[str, s.Type] = {}
423
+ for member in union.members:
424
+ tag = _tag(member)
425
+ if tag is None:
426
+ raise SchemaError(
427
+ f"{where}: DiscriminatedUnion members must be scalars, enums or @native classes, not {member}"
428
+ )
429
+ if tag in tags:
430
+ raise SchemaError(
431
+ f"{where}: DiscriminatedUnion members {tags[tag]} and {member} share tag {tag!r}"
432
+ )
433
+ tags[tag] = member
434
+ else:
435
+ kinds: dict[tuple[str, ...], s.Type] = {}
436
+ for member in union.members:
437
+ kind = s.wire_kind(member)
438
+ if kind in kinds:
439
+ raise SchemaError(
440
+ f"{where}: union members {kinds[kind]} and {member} cannot be told apart when serialised "
441
+ f"(both are {kind[0]}): use DiscriminatedUnion"
442
+ )
443
+ kinds[kind] = member
444
+
445
+ def __check_tags(self):
446
+ tags: dict[str, type] = {}
447
+ for cls in [*self.__structs, *self.__enums]:
448
+ tag = (
449
+ native_info(cls).tag if cls in self.__structs else self.__enums[cls].tag
450
+ )
451
+ if tag in tags:
452
+ raise SchemaError(
453
+ f"{cls.__qualname__} and {tags[tag].__qualname__} have the same tag {tag!r}"
454
+ )
455
+ tags[tag] = cls
456
+
457
+ def __recursive_cycles(self) -> dict[type, frozenset[type]]:
458
+ """For each struct in a cycle of types held by value, the other structs in that cycle"""
459
+ for raw in self.__structs.values():
460
+ for _, t, _ in raw.fields:
461
+ for ref, _ in _struct_refs(t):
462
+ if ref.cls not in self.__structs:
463
+ raise SchemaError(
464
+ f"{ref.cls.__qualname__} is not a module-level class of {ref.module}"
465
+ )
466
+
467
+ edges = {
468
+ cls: [
469
+ ref.cls
470
+ for _, t, _ in raw.fields
471
+ for ref, by_value in _struct_refs(t)
472
+ if by_value
473
+ ]
474
+ for cls, raw in self.__structs.items()
475
+ }
476
+
477
+ cycles = {}
478
+ for component in _strongly_connected(edges):
479
+ if len(component) > 1 or component[0] in edges[component[0]]:
480
+ modules = {c.__module__ for c in component}
481
+ if len(modules) > 1:
482
+ names = ", ".join(
483
+ f"{c.__module__}.{c.__qualname__}" for c in component
484
+ )
485
+ raise SchemaError(
486
+ f"Types in a cycle must be in the same module: {names}"
487
+ )
488
+ for cls in component:
489
+ cycles[cls] = frozenset(component)
490
+
491
+ return cycles
492
+
493
+ def __struct(self, raw: _RawStruct, cycle: frozenset[type]) -> s.Struct:
494
+ cls = raw.cls
495
+ return s.Struct(
496
+ module=cls.__module__,
497
+ name=cls.__name__,
498
+ tag=native_info(cls).tag,
499
+ fields=tuple(
500
+ s.Field(
501
+ name,
502
+ _indirect(t, cycle),
503
+ _default(cls, f, f"{cls.__qualname__}.{name}"),
504
+ )
505
+ for name, t, f in raw.fields
506
+ ),
507
+ cls=cls,
508
+ mutable=not cls.__dataclass_params__.frozen,
509
+ )
510
+
511
+
512
+ _ARRAY_ELEMENTS = (
513
+ *(s.Int(bits, signed) for bits in (8, 16, 32, 64) for signed in (True, False)),
514
+ s.Float(32),
515
+ s.Float(),
516
+ )
517
+ _ARRAY_ALONE = (
518
+ "an array may be a field, or None, but not within a tuple, Mapping or union"
519
+ )
520
+
521
+
522
+ def _array(np: Any, tp: Any, where: str) -> s.Array:
523
+ """The type of a numpy array, as numpy annotates one of a known number of dimensions: Matrix[np.float64], which
524
+ is np.ndarray[tuple[int, int], np.dtype[np.float64]]"""
525
+ shape, dtype = (*get_args(tp), None, None)[:2]
526
+ while isinstance(shape, typing.TypeAliasType):
527
+ shape = shape.__value__
528
+ sizes = get_args(shape)
529
+ if get_origin(shape) is not tuple or not sizes or any(n is not int for n in sizes):
530
+ raise SchemaError(
531
+ f"{where}: unsupported array {tp}: its number of dimensions must be given. Use Vector[np.float64], "
532
+ "Matrix[np.float64], or np.ndarray[tuple[int, int, int], np.dtype[np.float64]]"
533
+ )
534
+
535
+ (scalar,) = get_args(dtype) or (None,)
536
+ for element in _ARRAY_ELEMENTS:
537
+ if scalar is getattr(np, s.Array(element).dtype):
538
+ return s.Array(element, len(sizes))
539
+ raise SchemaError(
540
+ f"{where}: unsupported array {tp}: use one of a sized int or float, e.g. Vector[np.float64]"
541
+ )
542
+
543
+
544
+ def _decimal(metadata: Iterable[Any], where: str) -> s.Decimal:
545
+ """The type of a Decimal, whose number of decimal places is in its annotation: ours, or pydantic's"""
546
+ for m in metadata:
547
+ # pydantic's Field holds what it was given in its own metadata
548
+ for item in (m, *(getattr(m, "metadata", None) or ())):
549
+ places = getattr(item, "decimal_places", None)
550
+ if type(places) is int and 0 <= places <= s.DECIMAL_DIGITS:
551
+ return s.Decimal(places)
552
+ raise SchemaError(
553
+ f"{where}: a Decimal needs its number of decimal places, of 0 to {s.DECIMAL_DIGITS}: "
554
+ "Annotated[Decimal, DecimalPlaces(2)]"
555
+ )
556
+
557
+
558
+ def _written(t: s.Type) -> s.Type:
559
+ """t, as the field of a class which is not frozen: its array may be written to"""
560
+ match t:
561
+ case s.Array():
562
+ return replace(t, writeable=True)
563
+ case s.Optional(inner):
564
+ return s.Optional(_written(inner))
565
+ case _:
566
+ return t
567
+
568
+
569
+ def _arrays_alone(t: s.Type, where: str) -> s.Type:
570
+ """t, having checked that an array is not within a container"""
571
+ alone = t.inner if isinstance(t, s.Optional) else t
572
+ if any(isinstance(inner, s.Array) and inner is not alone for inner in walk(t)):
573
+ raise SchemaError(f"{where}: {_ARRAY_ALONE}")
574
+ return t
575
+
576
+
577
+ def _tag(t: s.Type) -> str | None:
578
+ match t:
579
+ case s.Int(bits=64, signed=True):
580
+ return "int"
581
+ case s.Int(bits=bits, signed=signed):
582
+ return f"{'' if signed else 'u'}int{bits}"
583
+ case s.Float(bits=64):
584
+ return "float"
585
+ case s.Float(bits=bits):
586
+ return f"float{bits}"
587
+ case (
588
+ s.Bool()
589
+ | s.Str()
590
+ | s.Bytes()
591
+ | s.Date()
592
+ | s.Time()
593
+ | s.DateTime()
594
+ | s.NaiveDateTime()
595
+ | s.TimeDelta()
596
+ | s.Uuid()
597
+ | s.Decimal()
598
+ ):
599
+ return type(t).__name__.lower()
600
+ case s.EnumRef(cls=cls):
601
+ return f"{cls.__module__}.{cls.__qualname__}"
602
+ case s.StructRef(cls=cls) | s.Shared(target=s.StructRef(cls=cls)):
603
+ return native_info(cls).tag
604
+ case _:
605
+ return None
606
+
607
+
608
+ def walk(t: s.Type) -> Iterator[s.Type]:
609
+ """t and all the types within it"""
610
+ yield t
611
+ match t:
612
+ case s.Optional(inner):
613
+ yield from walk(inner)
614
+ case s.Sequence(element) | s.Set(element):
615
+ yield from walk(element)
616
+ case s.Tuple(members) | s.Union(members):
617
+ for member in members:
618
+ yield from walk(member)
619
+ case s.Map(key, value):
620
+ yield from walk(key)
621
+ yield from walk(value)
622
+ case s.Shared(target) | s.Indirect(target):
623
+ yield target
624
+
625
+
626
+ def _struct_refs(
627
+ t: s.Type, by_value: bool = True
628
+ ) -> Iterator[tuple[s.StructRef, bool]]:
629
+ """
630
+ The structs t refers to, and whether each is held by value. Those in sequences are not, as the sequence's
631
+ storage is out of line, so it may hold a type being defined (std::vector, Vec)
632
+ """
633
+ match t:
634
+ case s.StructRef():
635
+ # A mutable class is held by reference
636
+ yield t, by_value and not t.mutable
637
+ case s.Shared(target) | s.Indirect(target):
638
+ yield target, False
639
+ case s.Optional(inner):
640
+ yield from _struct_refs(inner, by_value)
641
+ case s.Sequence(element):
642
+ yield from _struct_refs(element, False)
643
+ case s.Tuple(members) | s.Union(members):
644
+ for member in members:
645
+ yield from _struct_refs(member, by_value)
646
+ case s.Map(_, value):
647
+ yield from _struct_refs(value, by_value)
648
+ case _:
649
+ pass
650
+
651
+
652
+ def _indirect(t: s.Type, cycle: frozenset[type]) -> s.Type:
653
+ """t, with the structs it holds by value that are in its struct's cycle made Indirect"""
654
+ if not cycle:
655
+ return t
656
+
657
+ match t:
658
+ case s.StructRef(cls=cls, mutable=False) if cls in cycle:
659
+ return s.Indirect(t)
660
+ case s.Optional(inner):
661
+ return s.Optional(_indirect(inner, cycle))
662
+ case s.Tuple(members):
663
+ return s.Tuple(tuple(_indirect(m, cycle) for m in members))
664
+ case s.Union(members, discriminated):
665
+ return s.Union(tuple(_indirect(m, cycle) for m in members), discriminated)
666
+ case s.Map(key, value):
667
+ return s.Map(key, _indirect(value, cycle))
668
+ case _:
669
+ return t
670
+
671
+
672
+ def _default(cls: type, f: Field, where: str) -> Any:
673
+ default, factory = f.default, f.default_factory
674
+ # Of a pydantic dataclass, a field's default may be a pydantic Field(), which has them
675
+ if info := getattr(cls, "__pydantic_fields__", {}).get(f.name):
676
+ factory = info.default_factory or MISSING
677
+ default = (
678
+ MISSING if info.is_required() or info.default_factory else info.default
679
+ )
680
+
681
+ if default is not MISSING:
682
+ return default
683
+
684
+ if factory is MISSING:
685
+ return s.NO_DEFAULT
686
+
687
+ if factory in (tuple, frozenset, dict) or (
688
+ isinstance(factory, type) and is_native(factory)
689
+ ):
690
+ return factory()
691
+
692
+ raise SchemaError(
693
+ f"{where}: default_factory {factory!r} is not supported: only tuple, frozenset, dict or a @native class, "
694
+ "as a default must be the same in each language"
695
+ )
696
+
697
+
698
+ def _check_defaults(schema: s.Schema):
699
+ for module in schema.modules.values():
700
+ for struct in module.structs:
701
+ for f in struct.fields:
702
+ if f.has_default and not s.conforms(f.type, f.default, schema):
703
+ raise SchemaError(
704
+ f"{struct.cls.__qualname__}.{f.name}: default {f.default!r} does not conform to its type"
705
+ )
706
+
707
+
708
+ def _strongly_connected(edges: dict[type, list[type]]) -> list[list[type]]:
709
+ """Tarjan's algorithm"""
710
+ index: dict[type, int] = {}
711
+ low: dict[type, int] = {}
712
+ stack: list[type] = []
713
+ on_stack: set[type] = set()
714
+ components: list[list[type]] = []
715
+
716
+ def visit(node: type):
717
+ index[node] = low[node] = len(index)
718
+ stack.append(node)
719
+ on_stack.add(node)
720
+
721
+ for target in edges[node]:
722
+ if target not in index:
723
+ visit(target)
724
+ low[node] = min(low[node], low[target])
725
+ elif target in on_stack:
726
+ low[node] = min(low[node], index[target])
727
+
728
+ if low[node] == index[node]:
729
+ component = []
730
+ while True:
731
+ member = stack.pop()
732
+ on_stack.discard(member)
733
+ component.append(member)
734
+ if member is node:
735
+ break
736
+ components.append(component)
737
+
738
+ for node in edges:
739
+ if node not in index:
740
+ visit(node)
741
+
742
+ return components
743
+
744
+
745
+ def _ordered(structs: list[s.Struct]) -> tuple[s.Struct, ...]:
746
+ """In definition order, except that each follows the structs of its module it holds by value"""
747
+ names = {st.name for st in structs}
748
+ needs = {
749
+ st.name: {
750
+ ref.name
751
+ for f in st.fields
752
+ for ref, by_value in _struct_refs(f.type)
753
+ if by_value and ref.module == st.module and ref.name in names
754
+ }
755
+ for st in structs
756
+ }
757
+
758
+ ordered: list[s.Struct] = []
759
+ done: set[str] = set()
760
+ remaining = list(structs)
761
+ while remaining:
762
+ st = next(st for st in remaining if needs[st.name] <= done)
763
+ ordered.append(st)
764
+ done.add(st.name)
765
+ remaining.remove(st)
766
+
767
+ return tuple(ordered)
768
+
769
+
770
+ def _dependencies(name: str, structs: list[s.Struct]) -> tuple[str, ...]:
771
+ modules = {
772
+ t.module
773
+ for st in structs
774
+ for f in st.fields
775
+ for t in walk(f.type)
776
+ if isinstance(t, s.StructRef | s.EnumRef)
777
+ }
778
+ return tuple(sorted(modules - {name}))
779
+
780
+
781
+ def _check_module_cycles(modules: dict[str, s.Module]):
782
+ visiting: list[str] = []
783
+ done: set[str] = set()
784
+
785
+ def visit(name: str):
786
+ if name in visiting:
787
+ cycle = " -> ".join([*visiting[visiting.index(name) :], name])
788
+ raise SchemaError(f"Modules cannot use each other's types: {cycle}")
789
+ if name in done or name not in modules:
790
+ return
791
+ visiting.append(name)
792
+ for dependency in modules[name].dependencies:
793
+ visit(dependency)
794
+ visiting.pop()
795
+ done.add(name)
796
+
797
+ for module in modules:
798
+ visit(module)
799
+
800
+
801
+ def loaded_modules(package: str) -> list[str]:
802
+ """The modules of an imported package, and its subpackages, defining @native classes"""
803
+ prefix = package + "."
804
+ return sorted(
805
+ {
806
+ cls.__module__
807
+ for cls in list(_registry)
808
+ if cls.__module__ == package or cls.__module__.startswith(prefix)
809
+ }
810
+ & set(sys.modules)
811
+ )