binal 0.1.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.
@@ -0,0 +1,474 @@
1
+ """Annotation resolution and schema compilation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import enum
6
+ import typing
7
+ from dataclasses import dataclass, field
8
+ from types import UnionType
9
+ from typing import Any, cast, get_args, get_origin
10
+
11
+ from ..checksum import Checksum
12
+ from ..codecs import Codec
13
+ from ..constraints import Custom, MaxLength, MinLength, Pattern, Range
14
+ from ..errors import SchemaError
15
+ from ..fields import (
16
+ Align,
17
+ Array,
18
+ Bits,
19
+ CountOf,
20
+ EnumField,
21
+ Fixed,
22
+ LengthOf,
23
+ Magic,
24
+ NullTerminated,
25
+ Padding,
26
+ Prefixed,
27
+ Sized,
28
+ TaggedUnion,
29
+ When,
30
+ )
31
+ from ..types import BoolCodec, FloatCodec, IntegerCodec, VarIntCodec
32
+
33
+ _MISSING = object()
34
+
35
+
36
+ @dataclass
37
+ class FieldSpec:
38
+ name: str
39
+ annotation: Any = None
40
+ origin: Any = None
41
+ metadata: tuple[Any, ...] = ()
42
+ default: Any = _MISSING
43
+ has_default: bool = False
44
+ # Kind: int, float, bool, bytes, str, list, model, bitmodel, enum,
45
+ # union, codec, varint
46
+ kind: str = ""
47
+ int_spec: IntegerCodec | None = None
48
+ float_spec: FloatCodec | None = None
49
+ varint_spec: VarIntCodec | None = None
50
+ element: Any = None # annotation of list element
51
+ element_spec: FieldSpec | None = None
52
+ nested: Any = None # nested model class
53
+ enum_type: Any = None
54
+ union_types: tuple[Any, ...] = ()
55
+ codec: Any = None # Codec instance or class
56
+ codec_storage_spec: FieldSpec | None = None
57
+ prefixed: Prefixed | None = None
58
+ fixed: Fixed | None = None
59
+ null_terminated: NullTerminated | None = None
60
+ array: Array | None = None
61
+ bits: Bits | None = None
62
+ enum_field: EnumField | None = None
63
+ when: When | None = None
64
+ length_of: LengthOf | None = None
65
+ count_of: CountOf | None = None
66
+ sized: Sized | None = None
67
+ magic: Magic | None = None
68
+ padding: Padding | None = None
69
+ checksum: Checksum | None = None
70
+ align: Align | None = None
71
+ tagged_union: TaggedUnion | None = None
72
+ constraints: list[Any] = field(default_factory=list[Any])
73
+ fixed_size: int | None = None
74
+ is_derived: bool = False
75
+
76
+ @property
77
+ def is_init_field(self) -> bool:
78
+ return not self.is_derived
79
+
80
+
81
+ def _flatten_metadata(metadata: tuple[Any, ...]) -> tuple[Any, ...]:
82
+ flat: list[Any] = []
83
+ for meta in metadata:
84
+ if hasattr(meta, "__metadata__"):
85
+ # Nested Annotated alias, e.g. Annotated[int, Integer(24)].
86
+ flat.extend(_flatten_metadata(tuple(meta.__metadata__))) # type: ignore[attr-defined]
87
+ else:
88
+ flat.append(meta)
89
+ return tuple(flat)
90
+
91
+
92
+ def split_annotated(ann: Any) -> tuple[Any, tuple[Any, ...]]:
93
+ # typing.get_origin(Annotated[int, x]) returns Annotated in py3.11+
94
+ # get_args returns (int, x, ...)
95
+ if get_origin(ann) is not None:
96
+ args = get_args(ann)
97
+ # Annotated is detected by origin being Annotated-like; check first
98
+ # arg handling via __metadata__ attribute as fallback.
99
+ if hasattr(ann, "__metadata__"):
100
+ return ann.__origin__, _flatten_metadata(tuple(ann.__metadata__)) # type: ignore[attr-defined]
101
+ if args:
102
+ return args[0], _flatten_metadata(tuple(args[1:]))
103
+ if hasattr(ann, "__metadata__"):
104
+ return ann.__origin__, _flatten_metadata(tuple(ann.__metadata__)) # type: ignore[attr-defined]
105
+ return ann, ()
106
+
107
+
108
+ def _parse_primitive_spec(
109
+ spec: FieldSpec, base: Any, metadata: tuple[Any, ...]
110
+ ) -> None:
111
+ for meta in metadata:
112
+ if isinstance(meta, IntegerCodec):
113
+ spec.int_spec = meta
114
+ spec.kind = "int"
115
+ elif isinstance(meta, FloatCodec):
116
+ spec.float_spec = meta
117
+ spec.kind = "float"
118
+ elif isinstance(meta, BoolCodec):
119
+ spec.kind = "bool"
120
+ elif isinstance(meta, VarIntCodec):
121
+ spec.varint_spec = meta
122
+ spec.kind = "varint"
123
+ elif isinstance(meta, Bits):
124
+ spec.bits = meta
125
+ spec.kind = "bit"
126
+ elif isinstance(meta, Codec) or type(meta) is type and issubclass(meta, Codec):
127
+ spec.codec = meta
128
+ elif isinstance(meta, (Range, MaxLength, MinLength, Pattern, Custom)):
129
+ spec.constraints.append(meta)
130
+
131
+
132
+ def _int_fixed_size(spec: FieldSpec) -> int | None:
133
+ if spec.int_spec is not None and spec.int_spec.bits % 8 == 0:
134
+ return spec.int_spec.bits // 8
135
+ if spec.int_spec is not None:
136
+ return None # bit-level
137
+ return None
138
+
139
+
140
+ def _compile_element(ann: Any, name: str) -> FieldSpec:
141
+ """Compile a list element annotation into a FieldSpec."""
142
+ base, metadata = split_annotated(ann)
143
+ sub = FieldSpec(name=name, annotation=ann, origin=base, metadata=metadata)
144
+ _parse_primitive_spec(sub, base, metadata)
145
+ # Nested model element.
146
+ if isinstance(base, type):
147
+ try:
148
+ from ..model import BinaryModel, BitModel # local import to avoid cycle
149
+
150
+ if issubclass(base, (BinaryModel, BitModel)):
151
+ sub.nested = base
152
+ sub.kind = "model"
153
+ return sub
154
+ except (ImportError, TypeError):
155
+ pass
156
+ if issubclass(base, enum.Enum):
157
+ sub.enum_type = base
158
+ sub.kind = "enum"
159
+ sub.enum_field = EnumField(_default_int_for_enum())
160
+ return sub
161
+ if base is int and sub.kind == "":
162
+ raise SchemaError(
163
+ f"Field '{name}': bare int in collection needs a binary type (e.g. UInt8)"
164
+ )
165
+ if base is float and sub.kind == "":
166
+ raise SchemaError(
167
+ f"Field '{name}': bare float in collection needs a binary type (e.g. Float32)"
168
+ )
169
+ if base is bytes:
170
+ sub.kind = "bytes"
171
+ if base is str:
172
+ sub.kind = "str"
173
+ return sub
174
+
175
+
176
+ def _default_int_for_enum() -> Any:
177
+ from ..types import UInt8
178
+
179
+ return UInt8
180
+
181
+
182
+ def compile_fields(cls: Any) -> list[FieldSpec]:
183
+ """Compile a model class's annotations into field specs."""
184
+ try:
185
+ hints = typing.get_type_hints(cls, include_extras=True)
186
+ except Exception as exc:
187
+ raise SchemaError(
188
+ f"Cannot resolve annotations for {cls.__name__}: {exc}"
189
+ ) from exc
190
+
191
+ # Preserve definition order from __annotations__.
192
+ names = list(getattr(cls, "__annotations__", {}).keys())
193
+ # get_type_hints may include inherited fields; include them in order.
194
+ for name in hints:
195
+ if name not in names:
196
+ names.append(name)
197
+
198
+ specs: list[FieldSpec] = []
199
+ for name in names:
200
+ if name.startswith("_"):
201
+ continue
202
+ ann = hints[name]
203
+ spec = _compile_one(cls, name, ann)
204
+ specs.append(spec)
205
+
206
+ _validate_dependencies(cls, specs)
207
+ return specs
208
+
209
+
210
+ def _compile_one(cls: Any, name: str, ann: Any) -> FieldSpec:
211
+ base, metadata = split_annotated(ann)
212
+ spec = FieldSpec(name=name, annotation=ann, origin=base, metadata=metadata)
213
+
214
+ # Class-level default.
215
+ if name in getattr(cls, "__dict__", {}):
216
+ spec.default = cls.__dict__[name]
217
+ spec.has_default = True
218
+
219
+ # Collect markers first.
220
+ for meta in metadata:
221
+ if isinstance(meta, Prefixed):
222
+ spec.prefixed = meta
223
+ elif isinstance(meta, Fixed):
224
+ spec.fixed = meta
225
+ elif isinstance(meta, NullTerminated):
226
+ spec.null_terminated = meta
227
+ elif isinstance(meta, Array):
228
+ spec.array = meta
229
+ elif isinstance(meta, EnumField):
230
+ spec.enum_field = meta
231
+ elif isinstance(meta, When):
232
+ spec.when = meta
233
+ elif isinstance(meta, LengthOf):
234
+ spec.length_of = meta
235
+ elif isinstance(meta, CountOf):
236
+ spec.count_of = meta
237
+ elif isinstance(meta, Sized):
238
+ spec.sized = meta
239
+ elif isinstance(meta, Magic):
240
+ spec.magic = meta
241
+ elif isinstance(meta, Padding):
242
+ spec.padding = meta
243
+ elif isinstance(meta, Checksum):
244
+ spec.checksum = meta
245
+ elif isinstance(meta, Align):
246
+ spec.align = meta
247
+ elif isinstance(meta, TaggedUnion):
248
+ spec.tagged_union = meta
249
+ elif isinstance(meta, (Range, MaxLength, MinLength, Pattern, Custom)):
250
+ spec.constraints.append(meta)
251
+
252
+ _parse_primitive_spec(spec, base, metadata)
253
+
254
+ # Codec (instance or class) in metadata.
255
+ for meta in metadata:
256
+ if isinstance(meta, Codec) or (
257
+ isinstance(meta, type) and issubclass(meta, Codec)
258
+ ):
259
+ spec.codec = meta
260
+ spec.kind = "codec"
261
+ storage = getattr(cast(Any, meta), "storage", None)
262
+ if storage is not None:
263
+ storage_base, storage_meta = split_annotated(storage)
264
+ storage_spec = FieldSpec(
265
+ name=name, annotation=storage, origin=storage_base
266
+ )
267
+ _parse_primitive_spec(storage_spec, storage_base, storage_meta)
268
+ # Storage may be a nested model or primitive.
269
+ if isinstance(storage_base, type):
270
+ try:
271
+ from ..model import BinaryModel, BitModel
272
+
273
+ if issubclass(storage_base, (BinaryModel, BitModel)):
274
+ storage_spec.nested = storage_base
275
+ storage_spec.kind = "model"
276
+ except (ImportError, TypeError):
277
+ pass
278
+ spec.codec_storage_spec = storage_spec
279
+ break
280
+
281
+ if spec.magic is not None:
282
+ spec.kind = "magic"
283
+ spec.fixed_size = len(spec.magic.value)
284
+ spec.is_derived = True
285
+ return spec
286
+ if spec.padding is not None:
287
+ spec.kind = "padding"
288
+ spec.fixed_size = spec.padding.length
289
+ spec.is_derived = True
290
+ return spec
291
+ if spec.checksum is not None:
292
+ # Checksum field type determines its size (e.g. UInt32 -> 4).
293
+ spec.kind = "checksum"
294
+ spec.is_derived = True
295
+ if spec.int_spec is not None:
296
+ spec.fixed_size = _int_fixed_size(spec)
297
+ return spec
298
+ if spec.length_of is not None or spec.count_of is not None:
299
+ spec.kind = "derived"
300
+ spec.is_derived = True
301
+ if spec.int_spec is not None:
302
+ spec.fixed_size = _int_fixed_size(spec)
303
+ return spec
304
+
305
+ # Union / Optional.
306
+ origin = get_origin(base)
307
+ if origin is UnionType or origin is typing.Union:
308
+ args = get_args(base)
309
+ non_none = tuple(a for a in args if a is not type(None))
310
+ if len(non_none) == 1 and len(args) == 2:
311
+ # Optional[X] – treat as X with When usually present.
312
+ inner = _compile_one(cls, name, non_none[0])
313
+ # Preserve outer markers.
314
+ inner.name = name
315
+ inner.annotation = ann
316
+ inner.when = spec.when or inner.when
317
+ inner.constraints = spec.constraints + inner.constraints
318
+ inner.default = spec.default
319
+ inner.has_default = spec.has_default
320
+ if inner.default is _MISSING and not inner.has_default:
321
+ inner.has_default = True
322
+ inner.default = None
323
+ return inner
324
+ spec.kind = "union"
325
+ spec.union_types = args
326
+ return spec
327
+
328
+ # List / collections.
329
+ if origin is list or base is list:
330
+ args = get_args(base)
331
+ elem_ann = args[0] if args else Any
332
+ spec.kind = "list"
333
+ spec.element = elem_ann
334
+ spec.element_spec = _compile_element(elem_ann, name)
335
+ if spec.array is None:
336
+ raise SchemaError(
337
+ f"Field '{name}': list fields need Array(...) metadata, "
338
+ "e.g. Annotated[list[Float32], Array(count_prefix=UInt16)]"
339
+ )
340
+ return spec
341
+
342
+ # Nested model.
343
+ if isinstance(base, type):
344
+ try:
345
+ from ..model import BinaryModel, BitModel
346
+
347
+ if issubclass(base, (BinaryModel, BitModel)):
348
+ spec.kind = "model"
349
+ spec.nested = base
350
+ return spec
351
+ except (ImportError, TypeError):
352
+ pass
353
+ if issubclass(base, enum.Enum):
354
+ spec.kind = "enum"
355
+ spec.enum_type = base
356
+ if spec.enum_field is None:
357
+ spec.enum_field = EnumField(_default_int_for_enum())
358
+ # Underlying size.
359
+ _underlying_base, underlying_meta = split_annotated(
360
+ spec.enum_field.underlying
361
+ )
362
+ for m in underlying_meta:
363
+ if isinstance(m, IntegerCodec):
364
+ spec.int_spec = m
365
+ spec.fixed_size = _int_fixed_size(spec)
366
+ return spec
367
+
368
+ # Primitive types.
369
+ if base is int:
370
+ if spec.kind == "bit":
371
+ return spec
372
+ if spec.int_spec is None and spec.varint_spec is None:
373
+ raise SchemaError(
374
+ f"Field '{name}': bare int needs a binary type "
375
+ "(e.g. UInt8, Int32, ULEB128, or Annotated[int, Bits(3)])"
376
+ )
377
+ if spec.kind == "":
378
+ spec.kind = "int"
379
+ spec.fixed_size = _int_fixed_size(spec)
380
+ return spec
381
+ if base is float:
382
+ if spec.float_spec is None:
383
+ raise SchemaError(
384
+ f"Field '{name}': bare float needs a binary type (e.g. Float32)"
385
+ )
386
+ spec.kind = "float"
387
+ spec.fixed_size = spec.float_spec.bits // 8
388
+ return spec
389
+ if base is bool:
390
+ spec.kind = "bool"
391
+ if spec.bits is not None:
392
+ spec.kind = "bit"
393
+ else:
394
+ spec.fixed_size = 1
395
+ return spec
396
+ if base is bytes:
397
+ spec.kind = "bytes"
398
+ if spec.fixed is not None:
399
+ spec.fixed_size = spec.fixed.length
400
+ return spec
401
+ if base is str:
402
+ if (
403
+ spec.fixed is None
404
+ and spec.prefixed is None
405
+ and spec.null_terminated is None
406
+ and spec.sized is None
407
+ ):
408
+ raise SchemaError(
409
+ f"Field '{name}': str needs Fixed, Prefixed, NullTerminated, or Sized metadata"
410
+ )
411
+ spec.kind = "str"
412
+ if spec.fixed is not None:
413
+ spec.fixed_size = spec.fixed.length
414
+ return spec
415
+
416
+ # Codec already handled above.
417
+ if spec.kind == "codec":
418
+ return spec
419
+
420
+ raise SchemaError(f"Field '{name}': unsupported type {ann!r}")
421
+
422
+
423
+ def _validate_dependencies(cls: Any, specs: list[FieldSpec]) -> None:
424
+ names = {s.name for s in specs}
425
+ for spec in specs:
426
+ refs: list[str] = []
427
+ if spec.when is not None:
428
+ refs.append(spec.when.field)
429
+ if spec.length_of is not None:
430
+ refs.append(spec.length_of.field)
431
+ if spec.count_of is not None:
432
+ refs.append(spec.count_of.field)
433
+ if spec.sized is not None:
434
+ refs.append(spec.sized.field)
435
+ if spec.checksum is not None:
436
+ refs.extend(spec.checksum.fields)
437
+ if spec.tagged_union is not None:
438
+ refs.append(spec.tagged_union.discriminator)
439
+ if spec.array is not None and isinstance(spec.array.count, str):
440
+ refs.append(spec.array.count)
441
+ for ref in refs:
442
+ if ref not in names:
443
+ raise SchemaError(
444
+ f"Field '{spec.name}': references unknown field '{ref}' in {cls.__name__}"
445
+ )
446
+ if ref == spec.name:
447
+ raise SchemaError(f"Field '{spec.name}': cannot reference itself")
448
+
449
+
450
+ def compute_fixed_size(specs: list[FieldSpec]) -> int | None:
451
+ """Total fixed size in bytes, or None if any field is dynamic."""
452
+ total = 0
453
+ for spec in specs:
454
+ if spec.when is not None:
455
+ return None
456
+ if spec.kind in ("bytes", "str", "list", "union", "varint"):
457
+ # Dynamic unless fixed / sized with known size.
458
+ if spec.fixed is not None:
459
+ total += spec.fixed.length
460
+ continue
461
+ return None
462
+ if spec.kind == "model" and spec.nested is not None:
463
+ nested_size = spec.nested.fixed_size()
464
+ if nested_size is None:
465
+ return None
466
+ total += nested_size
467
+ continue
468
+ if spec.fixed_size is None:
469
+ return None
470
+ total += spec.fixed_size
471
+ return total
472
+
473
+
474
+ __all__ = ["FieldSpec", "compile_fields", "compute_fixed_size"]