From 2d73c4de9adfc3e083c78d878a2023fde1f60499 Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Sun, 9 Aug 2026 21:15:55 +0000 Subject: [PATCH 01/14] Temp --- examples/datalog/datalog_struct.py | 10 + examples/datalog/printlog.py | 84 +- examples/datalog/writelog.py | 70 +- .../robotpy-wpilog/semiwrap/DataLogReader.yml | 13 +- .../tests/test_datalog_examples.py | 61 ++ .../tests/test_datalog_reader_auto.py | 828 ++++++++++++++++++ .../robotpy-wpilog/tests/test_wpilog.py | 104 +++ subprojects/robotpy-wpilog/wpilog/_datalog.py | 274 ++++++ .../tests/geometry/test_datalog_struct.py | 64 ++ subprojects/robotpy-wpiutil/meson.build | 1 + subprojects/robotpy-wpiutil/pyproject.in.toml | 1 + .../semiwrap/WPyStructSchema.yml | 69 ++ .../tests/test_schema_bridge.py | 562 ++++++++++++ .../robotpy-wpiutil/tests/test_struct.py | 53 ++ .../tests/test_struct_annotations.py | 644 ++++++++++++++ .../tests/test_struct_schema.py | 529 +++++++++++ .../wpiutil/src/wpistruct/wpystruct_fns.cpp | 8 +- .../src/wpistruct/wpystruct_schema.cpp | 727 +++++++++++++++ .../wpiutil/src/wpistruct/wpystruct_schema.h | 69 ++ .../wpiutil/wpistruct/__init__.py | 9 + .../wpiutil/wpistruct/_compiler.py | 699 +++++++++++++++ .../wpiutil/wpistruct/_schema.py | 428 +++++++++ .../wpiutil/wpistruct/dataclass.py | 273 +----- .../robotpy-wpiutil/wpiutil/wpistruct/desc.py | 6 + .../wpiutil/wpistruct/layout.py | 24 + 25 files changed, 5286 insertions(+), 324 deletions(-) create mode 100644 examples/datalog/datalog_struct.py create mode 100644 subprojects/robotpy-wpilog/tests/test_datalog_examples.py create mode 100644 subprojects/robotpy-wpilog/tests/test_datalog_reader_auto.py create mode 100644 subprojects/robotpy-wpilog/wpilog/_datalog.py create mode 100644 subprojects/robotpy-wpimath/tests/geometry/test_datalog_struct.py create mode 100644 subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml create mode 100644 subprojects/robotpy-wpiutil/tests/test_schema_bridge.py create mode 100644 subprojects/robotpy-wpiutil/tests/test_struct_annotations.py create mode 100644 subprojects/robotpy-wpiutil/tests/test_struct_schema.py create mode 100644 subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.cpp create mode 100644 subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.h create mode 100644 subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py create mode 100644 subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py create mode 100644 subprojects/robotpy-wpiutil/wpiutil/wpistruct/layout.py diff --git a/examples/datalog/datalog_struct.py b/examples/datalog/datalog_struct.py new file mode 100644 index 000000000..bb5c34376 --- /dev/null +++ b/examples/datalog/datalog_struct.py @@ -0,0 +1,10 @@ +import dataclasses + +from wpiutil import wpistruct + + +@wpistruct.make_wpistruct(name="ExampleRecord") +@dataclasses.dataclass +class ExampleRecord: + i: wpistruct.int32 = 0 + j: wpistruct.int32 = 0 diff --git a/examples/datalog/printlog.py b/examples/datalog/printlog.py index af8f5671c..2a9799ce0 100755 --- a/examples/datalog/printlog.py +++ b/examples/datalog/printlog.py @@ -5,88 +5,22 @@ # the WPILib BSD license file in the root directory of this project. import argparse -import datetime from wpilog import DataLogReader +from datalog_struct import ExampleRecord + if __name__ == "__main__": parser = argparse.ArgumentParser() + parser.add_argument("--predefined", action="store_true") parser.add_argument("infile") args = parser.parse_args() reader = DataLogReader(args.infile) + struct_types = (ExampleRecord,) if args.predefined else () - entries = {} - for record in reader: - timestamp = record.get_timestamp() / 1000000 - if record.is_start(): - try: - data = record.get_start_data() - print(f"{data} [{timestamp}]") - if data.entry in entries: - print("...DUPLICATE entry ID, overriding") - entries[data.entry] = data - except TypeError as e: - print("Start(INVALID)") - elif record.is_finish(): - try: - entry = record.get_finish_entry() - print(f"Finish({entry}) [{timestamp}]") - if entry not in entries: - print("...ID not found") - else: - del entries[entry] - except TypeError as e: - print("Finish(INVALID)") - elif record.is_set_metadata(): - try: - data = record.get_set_metadata_data() - print(f"{data} [{timestamp}]") - if data.entry not in entries: - print("...ID not found") - except TypeError as e: - print("SetMetadata(INVALID)") - elif record.is_control(): - print("Unrecognized control record") - else: - print(f"Data({record.get_entry()}, size={record.get_size()}) ", end="") - entry = entries.get(record.get_entry(), None) - if entry is None: - print("") - continue - print(f" [{timestamp}]") - - try: - # handle systemTime specially - if entry.name == "systemTime" and entry.type == "int64": - dt = datetime.fromtimestamp(record.get_integer() / 1000000) - print(f" {dt:%Y-%m-%d %H:%M:%S.%f}") - continue - - if entry.type == "double": - print(f" {record.get_double()}") - elif entry.type == "int64": - print(f" {record.get_integer()}") - elif entry.type == "string" or entry.type == "json": - print(f" '{record.get_string()}'") - elif entry.type == "boolean": - print(f" {record.get_boolean()}") - elif entry.type == "boolean[]": - arr = record.get_boolean_array() - print(f" {arr}") - elif entry.type == "double[]": - arr = record.get_double_array() - print(f" {arr}") - elif entry.type == "float[]": - arr = record.get_float_array() - print(f" {arr}") - elif entry.type == "int64[]": - arr = record.get_integer_array() - print(f" {arr}") - elif entry.type == "string[]": - arr = record.get_string_array() - print(f" {arr}") - elif entry.type == "raw": - print(f" {record.get_raw()}") - except TypeError as e: - print(" invalid", e) + for record, entry, value in reader.iter_auto(*struct_types): + timestamp = record.get_timestamp() / 1_000_000 + name = entry.name if entry is not None else f"entry:{record.get_entry()}" + advertised_type = entry.type if entry is not None else "unknown" + print(f"{name} [{advertised_type}] [{timestamp}] {value!r}") diff --git a/examples/datalog/writelog.py b/examples/datalog/writelog.py index fe3e612e9..cbb9d6e9c 100755 --- a/examples/datalog/writelog.py +++ b/examples/datalog/writelog.py @@ -2,8 +2,32 @@ import argparse import pathlib +import time + +import wpilog + +from datalog_struct import ExampleRecord + + +def _wait_for_complete_log(candidate_paths): + deadline = time.monotonic() + 5 + while True: + for path in candidate_paths(): + try: + values = wpilog.DataLogReader(str(path)).iter_auto(ExampleRecord) + record_count = sum( + entry is not None and entry.name == "/record" + for _, entry, _ in values + ) + except (OSError, ValueError): + continue + if record_count == 2: + return + + if time.monotonic() >= deadline: + raise TimeoutError("timed out waiting for the data log to flush") + time.sleep(0.01) -from wpilog import DataLog, BooleanLogEntry, StringArrayLogEntry, RawLogEntry if __name__ == "__main__": parser = argparse.ArgumentParser() @@ -11,18 +35,40 @@ args = parser.parse_args() if args.out.is_dir(): - datalog = DataLog(str(args.out)) + existing_paths = set(args.out.iterdir()) + datalog = wpilog.DataLogBackgroundWriter(str(args.out)) + + def candidate_paths(): + return set(args.out.iterdir()) - existing_paths + else: - datalog = DataLog(str(args.out.parent), args.out.name) + datalog = wpilog.DataLogBackgroundWriter(str(args.out.parent), args.out.name) + + def candidate_paths(): + return (args.out,) + + completed = False + try: + bools = wpilog.BooleanLogEntry(datalog, "/bools") + bools.append(True) + bools.append(False) - bools = BooleanLogEntry(datalog, "/bools") - bools.append(True) - bools.append(False) + strings = wpilog.StringArrayLogEntry(datalog, "/strings") + strings.append(["a", "b", "c"]) + strings.append(["d", "e", "f"]) - strings = StringArrayLogEntry(datalog, "/strings") - strings.append(["a", "b", "c"]) - strings.append(["d", "e", "f"]) + raw = wpilog.RawLogEntry(datalog, "/raws") + raw.append(b"\x01\x02\x03") + raw.append(b"\x04\x05\x06") - raw = RawLogEntry(datalog, "/raws") - raw.append(b"\x01\x02\x03") - raw.append(b"\x04\x05\x06") + record = wpilog.StructLogEntry(datalog, "/record", ExampleRecord) + record.append(ExampleRecord(1, 2)) + record.append(ExampleRecord(3, 4)) + completed = True + finally: + try: + if completed: + datalog.flush() + _wait_for_complete_log(candidate_paths) + finally: + datalog.stop() diff --git a/subprojects/robotpy-wpilog/semiwrap/DataLogReader.yml b/subprojects/robotpy-wpilog/semiwrap/DataLogReader.yml index 4a4af4153..742edc561 100644 --- a/subprojects/robotpy-wpilog/semiwrap/DataLogReader.yml +++ b/subprojects/robotpy-wpilog/semiwrap/DataLogReader.yml @@ -52,7 +52,8 @@ classes: } return ptr; } - return_value_policy: reference_internal + keepalive: + - [0, 1] GetFinishEntry: no_release_gil: true param_override: @@ -83,7 +84,8 @@ classes: } return ptr; } - return_value_policy: reference_internal + keepalive: + - [0, 1] GetBoolean: no_release_gil: true param_override: @@ -329,4 +331,11 @@ inline_code: | py::keep_alive<1, 2>()) .def("__iter__", [](wpi::log::DataLogReader * that) { return py::make_iterator(that->begin(), that->end()); + }, py::keep_alive<0,1>()) + .def("_iter_stable", [](wpi::log::DataLogReader *that) { + return py::make_iterator( + that->begin(), that->end(), py::keep_alive<0, 1>()); + }, py::keep_alive<0, 1>()) + .def("iter_auto", [](wpi::log::DataLogReader *self, py::args structTypes) { + return py::module_::import("wpilog._datalog").attr("_iter_auto")(self, structTypes); }, py::keep_alive<0,1>()); diff --git a/subprojects/robotpy-wpilog/tests/test_datalog_examples.py b/subprojects/robotpy-wpilog/tests/test_datalog_examples.py new file mode 100644 index 000000000..ff4bf6ad5 --- /dev/null +++ b/subprojects/robotpy-wpilog/tests/test_datalog_examples.py @@ -0,0 +1,61 @@ +import runpy +import subprocess +import sys +import types +from pathlib import Path + +import pytest +import wpilog + +EXAMPLE_DIR = Path(__file__).parents[3] / "examples" / "datalog" + + +def test_writelog_output_is_immediately_readable(tmp_path): + output = tmp_path / "example.wpilog" + + subprocess.run( + [sys.executable, str(EXAMPLE_DIR / "writelog.py"), str(output)], + check=True, + timeout=10, + ) + + values = list(wpilog.DataLogReader(str(output)).iter_auto()) + assert ( + sum(entry is not None and entry.name == "/record" for _, entry, _ in values) + == 2 + ) + + +def test_writelog_stops_background_writer_when_append_fails(monkeypatch, tmp_path): + writers = [] + + class FakeWriter: + def __init__(self, *args): + self.stopped = False + writers.append(self) + + def stop(self): + self.stopped = True + + class FailingEntry: + def __init__(self, *args): + pass + + def append(self, value): + raise RuntimeError("intentional append failure") + + fake_wpilog = types.ModuleType("wpilog") + fake_wpilog.DataLogBackgroundWriter = FakeWriter + fake_wpilog.BooleanLogEntry = FailingEntry + fake_wpilog.StringArrayLogEntry = FailingEntry + fake_wpilog.RawLogEntry = FailingEntry + fake_wpilog.StructLogEntry = FailingEntry + monkeypatch.setitem(sys.modules, "wpilog", fake_wpilog) + monkeypatch.syspath_prepend(str(EXAMPLE_DIR)) + monkeypatch.setattr(sys, "argv", ["writelog.py", str(tmp_path / "example.wpilog")]) + + with pytest.raises(RuntimeError, match="intentional append failure"): + runpy.run_path(str(EXAMPLE_DIR / "writelog.py"), run_name="__main__") + + assert len(writers) == 1 + assert writers[0].stopped diff --git a/subprojects/robotpy-wpilog/tests/test_datalog_reader_auto.py b/subprojects/robotpy-wpilog/tests/test_datalog_reader_auto.py new file mode 100644 index 000000000..4fa15302c --- /dev/null +++ b/subprojects/robotpy-wpilog/tests/test_datalog_reader_auto.py @@ -0,0 +1,828 @@ +import dataclasses +import gc +import weakref +from pathlib import Path + +import pytest +import wpilog +import wpilog._datalog as datalog_impl +from wpiutil import wpistruct + + +@wpistruct.make_wpistruct(name="Reading") +@dataclasses.dataclass +class Reading: + i: wpistruct.int32 = 0 + j: wpistruct.int32 = 0 + + +@wpistruct.make_wpistruct(name="ReadingChild") +@dataclasses.dataclass +class ReadingChild: + value: wpistruct.uint8 = 0 + + +@wpistruct.make_wpistruct(name="ReadingParent") +@dataclasses.dataclass +class ReadingParent: + child: ReadingChild = dataclasses.field(default_factory=ReadingChild) + + +def _read_auto(path: Path, *types): + return list(wpilog.DataLogReader(str(path)).iter_auto(*types)) + + +@pytest.mark.parametrize( + ("entry_cls", "value"), + [ + (wpilog.BooleanLogEntry, True), + (wpilog.IntegerLogEntry, -2), + (wpilog.FloatLogEntry, 1.5), + (wpilog.DoubleLogEntry, 2.5), + (wpilog.StringLogEntry, "hello"), + (wpilog.BooleanArrayLogEntry, [True, False]), + (wpilog.IntegerArrayLogEntry, [1, -2]), + (wpilog.FloatArrayLogEntry, [1.5, 2.5]), + (wpilog.DoubleArrayLogEntry, [3.5, 4.5]), + (wpilog.StringArrayLogEntry, ["a", "b"]), + ], +) +def test_iter_auto_decodes_primitives(tmp_path, entry_cls, value): + path = tmp_path / "primitive.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry_cls(log, "/value").append(value, 10) + + [(record, entry, decoded)] = _read_auto(path) + assert isinstance(record, wpilog.DataLogRecord) + assert entry.name == "/value" + assert decoded == value + + +def test_iter_auto_decodes_json_as_string(tmp_path): + path = tmp_path / "json.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry = log.start("/value", "json", "", 1) + log.append_string(entry, '{"enabled":true}', 10) + + [(record, start, decoded)] = _read_auto(path) + assert isinstance(record, wpilog.DataLogRecord) + assert start.type == "json" + assert decoded == '{"enabled":true}' + + +def test_iter_auto_decodes_raw_as_bytes(tmp_path): + path = tmp_path / "raw.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry = log.start("/value", "raw", "", 1) + log.append_raw(entry, b"\x00\x01", 10) + + [(record, start, decoded)] = _read_auto(path) + assert isinstance(record, wpilog.DataLogRecord) + assert start.type == "raw" + assert decoded == b"\x00\x01" + + +def test_iter_auto_returns_unknown_advertised_types_as_bytes(tmp_path): + path = tmp_path / "unknown.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry = log.start("/value", "vendor:unknown", "", 1) + log.append_raw(entry, b"unknown", 10) + + [(record, start, decoded)] = _read_auto(path) + assert isinstance(record, wpilog.DataLogRecord) + assert start.type == "vendor:unknown" + assert decoded == b"unknown" + + +def test_iter_auto_decodes_registered_struct(tmp_path): + path = tmp_path / "registered-struct.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + wpilog.StructLogEntry(log, "/reading", Reading).append(Reading(1, 2), 10) + + values = _read_auto(path, Reading) + schemas = [value for _, entry, value in values if entry.type == "structschema"] + readings = [value for _, entry, value in values if entry.type == "struct:Reading"] + + assert schemas == [Reading] + assert readings == [Reading(1, 2)] + + +def test_iter_auto_decodes_generated_struct(tmp_path): + path = tmp_path / "generated-struct.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + wpilog.StructLogEntry(log, "/reading", Reading).append(Reading(3, 4), 10) + + values = _read_auto(path) + [generated] = [value for _, entry, value in values if entry.type == "structschema"] + [instance] = [value for _, entry, value in values if entry.type == "struct:Reading"] + + assert isinstance(generated, type) + assert dataclasses.is_dataclass(generated) + assert type(instance) is generated + assert dataclasses.asdict(instance) == {"i": 3, "j": 4} + + +def test_iter_auto_decodes_registered_struct_array(tmp_path): + path = tmp_path / "registered-struct-array.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + wpilog.StructArrayLogEntry(log, "/readings", Reading).append( + [Reading(1, 2), Reading(3, 4)], 10 + ) + + values = _read_auto(path, Reading) + [readings] = [ + value for _, entry, value in values if entry.type == "struct:Reading[]" + ] + + assert readings == [Reading(1, 2), Reading(3, 4)] + + +def test_iter_auto_decodes_generated_struct_array(tmp_path): + path = tmp_path / "generated-struct-array.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + wpilog.StructArrayLogEntry(log, "/readings", Reading).append( + [Reading(5, 6), Reading(7, 8)], 10 + ) + + values = _read_auto(path) + [generated] = [value for _, entry, value in values if entry.type == "structschema"] + [readings] = [ + value for _, entry, value in values if entry.type == "struct:Reading[]" + ] + + assert all(type(reading) is generated for reading in readings) + assert [dataclasses.asdict(reading) for reading in readings] == [ + {"i": 5, "j": 6}, + {"i": 7, "j": 8}, + ] + + +def test_iter_auto_generated_type_is_reusable(tmp_path): + source = tmp_path / "source.wpilog" + with wpilog.DataLogWriter(str(source)) as log: + wpilog.StructLogEntry(log, "/reading", Reading).append(Reading(1, 2), 10) + + source_values = _read_auto(source) + generated = next( + value for _, entry, value in source_values if entry.type == "structschema" + ) + instance = next( + value for _, entry, value in source_values if entry.type == "struct:Reading" + ) + + destination = tmp_path / "destination.wpilog" + with wpilog.DataLogWriter(str(destination)) as log: + wpilog.StructLogEntry(log, "/copy", generated).append(instance, 20) + + copied = [ + value + for _, entry, value in _read_auto(destination, generated) + if entry.type == "struct:Reading" + ] + assert copied == [instance] + + +def test_iter_auto_generates_nested_structs_child_first(tmp_path): + path = tmp_path / "nested-struct.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + wpilog.StructLogEntry(log, "/parent", ReadingParent).append( + ReadingParent(ReadingChild(9)), 10 + ) + + values = _read_auto(path) + schema_values = [ + (entry.name, value) + for _, entry, value in values + if entry.type == "structschema" + ] + [parent] = [ + value for _, entry, value in values if entry.type == "struct:ReadingParent" + ] + + assert [name for name, _ in schema_values] == [ + "/.schema/struct:ReadingChild", + "/.schema/struct:ReadingParent", + ] + generated_child = schema_values[0][1] + generated_parent = schema_values[1][1] + assert type(parent) is generated_parent + assert type(parent.child) is generated_child + assert parent.child.value == 9 + + +def test_iter_auto_resolves_late_struct_schema_in_physical_order(tmp_path): + path = tmp_path / "late-schema.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry = log.start("/value", "struct:Late", "", 1) + log.append_raw(entry, b"\x01", 2) + log.add_schema("struct:Late", "structschema", "uint8 value", 3) + + values = _read_auto(path) + + assert [entry.type for _, entry, _ in values] == [ + "struct:Late", + "structschema", + ] + instance, generated = [value for _, _, value in values] + assert type(instance) is generated + assert instance.value == 1 + + +def test_iter_auto_resolves_late_struct_array_schema_in_physical_order(tmp_path): + path = tmp_path / "late-array-schema.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry = log.start("/values", "struct:Late[]", "", 1) + log.append_raw(entry, b"\x01\x02", 2) + log.add_schema("struct:Late", "structschema", "uint8 value", 3) + + values = _read_auto(path) + + assert [entry.type for _, entry, _ in values] == [ + "struct:Late[]", + "structschema", + ] + instances, generated = [value for _, _, value in values] + assert all(type(instance) is generated for instance in instances) + assert [instance.value for instance in instances] == [1, 2] + + +def test_iter_auto_missing_struct_registration_has_record_context(tmp_path): + path = tmp_path / "missing-schema.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry = log.start("/value", "struct:Missing", "", 1) + log.append_raw(entry, b"\x01", 2) + + with pytest.raises(ValueError) as exc_info: + _read_auto(path) + + message = str(exc_info.value) + assert "/value" in message + assert "struct:Missing" in message + assert "2" in message + + +def test_iter_auto_lookahead_retries_nested_schemas_and_preserves_order(tmp_path): + path = tmp_path / "nested-lookahead.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + parent_value = log.start("/parent", "struct:Parent", "", 1) + log.append_raw(parent_value, b"\x07", 2) + parent_schema = log.start("/.schema/struct:Parent", "structschema", "", 3) + log.append_string(parent_schema, "Child child", 4) + primitive = log.start("/primitive", "int64", "", 5) + log.append_integer(primitive, 42, 6) + child_schema = log.start("/.schema/struct:Child", "structschema", "", 7) + log.append_string(child_schema, "uint8 value", 8) + log.append_raw(parent_value, b"\x09", 9) + + values = _read_auto(path) + + assert [entry.type for _, entry, _ in values] == [ + "struct:Parent", + "structschema", + "int64", + "structschema", + "struct:Parent", + ] + first_parent, generated_parent, primitive_value, generated_child, second_parent = [ + value for _, _, value in values + ] + assert primitive_value == 42 + assert type(first_parent) is generated_parent + assert type(second_parent) is generated_parent + assert type(first_parent.child) is generated_child + assert type(second_parent.child) is generated_child + assert first_parent.child.value == 7 + assert second_parent.child.value == 9 + + +def test_iter_auto_lookahead_preserves_pending_schema_across_continuations(tmp_path): + path = tmp_path / "pending-across-lookahead.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + value_a = log.start("/a", "struct:A", "", 1) + log.append_raw(value_a, b"\x0a", 2) + value_b = log.start("/b", "struct:B", "", 3) + log.append_raw(value_b, b"\x0b", 4) + log.add_schema("struct:B", "structschema", "C child", 5) + log.add_schema("struct:A", "structschema", "uint8 value", 6) + log.add_schema("struct:C", "structschema", "uint8 value", 7) + + values = _read_auto(path) + + assert [entry.type for _, entry, _ in values] == [ + "struct:A", + "struct:B", + "structschema", + "structschema", + "structschema", + ] + instance_a, instance_b, generated_b, generated_a, generated_c = [ + value for _, _, value in values + ] + assert type(instance_a) is generated_a + assert type(instance_b) is generated_b + assert type(instance_b.child) is generated_c + assert instance_a.value == 10 + assert instance_b.child.value == 11 + + +def test_iter_auto_lookahead_preserves_same_type_schema_order(tmp_path): + path = tmp_path / "same-type-schema-order.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + value_a = log.start("/a", "struct:A", "", 1) + log.append_raw(value_a, b"\x07", 2) + first_a = log.start("/.schema/struct:A", "structschema", "", 3) + log.append_string(first_a, "Child child", 4) + log.finish(first_a, 5) + later_a = log.start("/.schema/struct:A", "structschema", "", 6) + log.append_string(later_a, "uint8 value", 7) + log.add_schema("struct:Child", "structschema", "uint8 value", 8) + + values = wpilog.DataLogReader(str(path)).iter_auto() + _, value_entry, instance_a = next(values) + _, first_schema_entry, generated_a = next(values) + + assert value_entry.type == "struct:A" + assert first_schema_entry.name == "/.schema/struct:A" + assert type(instance_a) is generated_a + assert instance_a.child.value == 7 + + with pytest.raises(ValueError, match="A"): + next(values) + + +def test_iter_auto_lookahead_drains_released_dependency_chain(tmp_path, monkeypatch): + path = tmp_path / "released-dependency-chain.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + target = log.start("/target", "struct:Target", "", 1) + log.append_raw(target, b"\x01", 2) + log.add_schema("struct:Outer", "structschema", "Wrapper wrapper", 3) + log.add_schema("struct:Wrapper", "structschema", "Target target", 4) + log.add_schema("struct:Target", "structschema", "uint8 value", 5) + + prepared = [] + original_prepare_schema = datalog_impl._prepare_schema + + def recording_prepare_schema(event, registry): + prepared.append(datalog_impl._schema_event_type_name(event)) + return original_prepare_schema(event, registry) + + monkeypatch.setattr(datalog_impl, "_prepare_schema", recording_prepare_schema) + iterator = wpilog.DataLogReader(str(path)).iter_auto() + first_value = next(iterator) + assert prepared.count("Outer") == 2 + assert prepared.count("Wrapper") == 2 + assert prepared.count("Target") == 1 + values = [first_value, *iterator] + + assert [entry.type for _, entry, _ in values] == [ + "struct:Target", + "structschema", + "structschema", + "structschema", + ] + target_value, generated_outer, generated_wrapper, generated_target = [ + value for _, _, value in values + ] + assert type(target_value) is generated_target + assert generated_outer.__dataclass_fields__["wrapper"].type is generated_wrapper + assert generated_wrapper.__dataclass_fields__["target"].type is generated_target + + +def test_iter_auto_lookahead_fetches_multiple_unknown_records_once( + tmp_path, monkeypatch +): + path = tmp_path / "multiple-unknown-lookahead.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + value_a = log.start("/a", "struct:A", "", 1) + log.append_raw(value_a, b"\x0a", 2) + value_b = log.start("/b", "struct:B", "", 3) + log.append_raw(value_b, b"\x0b", 4) + log.add_schema("struct:B", "structschema", "uint8 value", 5) + log.add_schema("struct:A", "structschema", "uint8 value", 6) + + fetched = [] + original_next_data_event = datalog_impl._next_data_event + + def recording_next_data_event(records, entries): + event = original_next_data_event(records, entries) + fetched.append((event.record.get_entry(), event.record.get_timestamp())) + return event + + monkeypatch.setattr(datalog_impl, "_next_data_event", recording_next_data_event) + values = _read_auto(path) + + assert [entry.type for _, entry, _ in values] == [ + "struct:A", + "struct:B", + "structschema", + "structschema", + ] + instance_a, instance_b, generated_b, generated_a = [value for _, _, value in values] + assert type(instance_a) is generated_a + assert type(instance_b) is generated_b + assert instance_a.value == 10 + assert instance_b.value == 11 + assert fetched == [ + (values[0][0].get_entry(), 2), + (values[1][0].get_entry(), 4), + (values[2][0].get_entry(), 5), + (values[3][0].get_entry(), 6), + ] + + +def test_iter_auto_lookahead_captures_reused_entry_lifecycle(tmp_path): + path = tmp_path / "reused-entry-lookahead.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + blocked = log.start("/blocked", "struct:Late", "", 1) + reused = log.start("/reused", "string", "old", 2) + log.append_raw(blocked, b"\x01", 3) + log.append_string(reused, "before-finish", 4) + log.finish(reused, 5) + log.append_raw(reused, b"orphan", 6) + new_reused = log.start("/reused", "int64", "new", 7) + assert new_reused == reused + log.append_integer(new_reused, 22, 8) + log.add_schema("struct:Late", "structschema", "uint8 value", 9) + + values = _read_auto(path) + + assert [ + value.value if index == 0 else value + for index, (_, _, value) in enumerate(values[:-1]) + ] == [ + 1, + "before-finish", + b"orphan", + 22, + ] + assert [entry.type if entry else None for _, entry, _ in values] == [ + "struct:Late", + "string", + None, + "int64", + "structschema", + ] + assert [entry.metadata if entry else None for _, entry, _ in values] == [ + "", + "old", + None, + "new", + "", + ] + + +def test_iter_auto_lookahead_defers_unrelated_malformed_schema(tmp_path): + path = tmp_path / "deferred-malformed-schema.wpilog" + malformed_text = "uint8 [2]" + with wpilog.DataLogWriter(str(path)) as log: + blocked = log.start("/blocked", "struct:Late", "", 1) + log.append_raw(blocked, b"\x01", 2) + malformed = log.start("/.schema/struct:Bad", "structschema", "", 3) + log.append_string(malformed, malformed_text, 4) + log.add_schema("struct:Late", "structschema", "uint8 value", 5) + + values = _read_auto(path) + + assert values[0][1].type == "struct:Late" + assert values[0][2].value == 1 + assert values[1][1].type == "structschema" + assert values[1][2] == malformed_text + assert isinstance(values[2][2], type) + + +def test_iter_auto_lookahead_defers_unrelated_invalid_utf8_schema(tmp_path): + path = tmp_path / "deferred-invalid-utf8-schema.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + blocked = log.start("/blocked", "struct:Late", "", 1) + log.append_raw(blocked, b"\x01", 2) + invalid = log.start("/.schema/struct:Invalid", "structschema", "", 3) + log.append_raw(invalid, b"\xff", 4) + log.add_schema("struct:Late", "structschema", "uint8 value", 5) + + values = wpilog.DataLogReader(str(path)).iter_auto() + _, blocked_entry, blocked_value = next(values) + assert blocked_entry.type == "struct:Late" + assert blocked_value.value == 1 + + with pytest.raises(UnicodeDecodeError): + next(values) + + +def test_iter_auto_lookahead_defers_unrelated_schema_conflict(tmp_path): + path = tmp_path / "deferred-schema-conflict.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + blocked = log.start("/blocked", "struct:Late", "", 1) + log.append_raw(blocked, b"\x01", 2) + first = log.start("/.schema/struct:Duplicate", "structschema", "", 3) + log.append_string(first, "uint8 value", 4) + log.finish(first, 5) + conflicting = log.start("/.schema/struct:Duplicate", "structschema", "", 6) + log.append_string(conflicting, "uint16 value", 7) + log.add_schema("struct:Late", "structschema", "uint8 value", 8) + + values = wpilog.DataLogReader(str(path)).iter_auto() + _, blocked_entry, blocked_value = next(values) + assert blocked_entry.type == "struct:Late" + assert blocked_value.value == 1 + + _, first_entry, generated = next(values) + assert first_entry.type == "structschema" + assert isinstance(generated, type) + + with pytest.raises(ValueError, match="Duplicate"): + next(values) + + +def test_iter_auto_parent_schema_before_child_raises(tmp_path): + path = tmp_path / "parent-before-child.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + parent = log.start("/.schema/struct:Parent", "structschema", "", 1) + log.append_string(parent, "Child child", 2) + child = log.start("/.schema/struct:Child", "structschema", "", 3) + log.append_string(child, "uint8 value", 4) + + with pytest.raises(ValueError, match="Child"): + _read_auto(path) + + +def test_iter_auto_malformed_schema_yields_text_then_value_raises(tmp_path): + path = tmp_path / "malformed-schema.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + schema = log.start("/.schema/struct:Bad", "structschema", "", 1) + log.append_string(schema, "uint8 [2]", 2) + value = log.start("/value", "struct:Bad", "", 3) + log.append_raw(value, b"\x01\x02", 4) + + values = wpilog.DataLogReader(str(path)).iter_auto() + schema_record, schema_entry, schema_value = next(values) + assert schema_record.get_timestamp() == 2 + assert schema_entry.type == "structschema" + assert schema_value == "uint8 [2]" + + with pytest.raises(ValueError, match=r"/value.*struct:Bad.*4"): + next(values) + + +def test_iter_auto_equivalent_duplicate_schemas_reuse_generated_type(tmp_path): + path = tmp_path / "duplicate-equivalent.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + first = log.start("/.schema/struct:Duplicate", "structschema", "", 1) + log.append_string(first, "uint8 value", 2) + log.finish(first, 3) + second = log.start("/.schema/struct:Duplicate", "structschema", "", 4) + log.append_string(second, " uint8 value; ", 5) + + schema_types = [value for _, _, value in _read_auto(path)] + assert len(schema_types) == 2 + assert schema_types[0] is schema_types[1] + + +def test_iter_auto_conflicting_duplicate_schemas_raise(tmp_path): + path = tmp_path / "duplicate-conflicting.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + first = log.start("/.schema/struct:Duplicate", "structschema", "", 1) + log.append_string(first, "uint8 value", 2) + log.finish(first, 3) + second = log.start("/.schema/struct:Duplicate", "structschema", "", 4) + log.append_string(second, "uint16 value", 5) + + values = wpilog.DataLogReader(str(path)).iter_auto() + first_record = next(values) + assert isinstance(first_record[2], type) + with pytest.raises(ValueError, match="Duplicate"): + next(values) + + +def test_iter_auto_supplied_type_precedes_incompatible_logged_schema(tmp_path): + path = tmp_path / "supplied-precedence.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + schema = log.start("/.schema/struct:Reading", "structschema", "", 1) + log.append_string(schema, "uint8 incompatible", 2) + value = log.start("/reading", "struct:Reading", "", 3) + log.append_raw(value, wpistruct.pack(Reading(11, 12)), 4) + + values = _read_auto(path, Reading) + assert [value for _, entry, value in values if entry.type == "structschema"] == [ + Reading + ] + assert [value for _, entry, value in values if entry.type == "struct:Reading"] == [ + Reading(11, 12) + ] + + +@pytest.mark.parametrize( + "schema_entry_name", + [ + "/.schema/struct:Reading", + "NT:/.schema/struct:Reading", + "custom:/.schema/struct:Reading", + ], +) +def test_iter_auto_recognizes_prefixed_schema_names(tmp_path, schema_entry_name): + path = tmp_path / "prefixed-schema.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + schema = log.start(schema_entry_name, "structschema", "", 1) + log.append_string(schema, "int32 i; int32 j", 2) + value = log.start("/reading", "struct:Reading", "", 3) + log.append_raw(value, wpistruct.pack(Reading(13, 14)), 4) + + values = _read_auto(path) + [generated] = [value for _, entry, value in values if entry.type == "structschema"] + [reading] = [value for _, entry, value in values if entry.type == "struct:Reading"] + assert type(reading) is generated + assert dataclasses.asdict(reading) == {"i": 13, "j": 14} + + +def test_iter_auto_uses_final_schema_marker(tmp_path): + path = tmp_path / "repeated-schema-marker.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + schema = log.start( + "old/.schema/struct:Ignored/custom/.schema/struct:Reading", + "structschema", + "", + 1, + ) + log.append_string(schema, "int32 i; int32 j", 2) + value = log.start("/reading", "struct:Reading", "", 3) + log.append_raw(value, wpistruct.pack(Reading(15, 16)), 4) + + values = _read_auto(path) + [generated] = [value for _, entry, value in values if entry.type == "structschema"] + [reading] = [value for _, entry, value in values if entry.type == "struct:Reading"] + assert wpistruct.get_type_name(generated) == "Reading" + assert type(reading) is generated + assert dataclasses.asdict(reading) == {"i": 15, "j": 16} + + +def test_iter_auto_ignores_empty_struct_schema_suffix(tmp_path): + path = tmp_path / "empty-schema-suffix.wpilog" + schema_text = "int32 i; int32 j" + with wpilog.DataLogWriter(str(path)) as log: + schema = log.start("custom:/.schema/struct:", "structschema", "", 1) + log.append_string(schema, schema_text, 2) + value = log.start("/reading", "struct:Reading", "", 3) + log.append_raw(value, wpistruct.pack(Reading(17, 18)), 4) + + values = wpilog.DataLogReader(str(path)).iter_auto() + _, schema_entry, schema_value = next(values) + assert schema_entry.name == "custom:/.schema/struct:" + assert schema_value == schema_text + with pytest.raises(ValueError, match=r"/reading.*struct:Reading.*4"): + next(values) + + +def test_iter_auto_ignores_unrecognized_structschema_entry_name(tmp_path): + path = tmp_path / "unrecognized-schema.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + schema = log.start("/.schema/protobuf:Reading", "structschema", "", 1) + log.append_string(schema, "int32 i; int32 j", 2) + value = log.start("/reading", "struct:Reading", "", 3) + log.append_raw(value, wpistruct.pack(Reading(15, 16)), 4) + + values = wpilog.DataLogReader(str(path)).iter_auto() + _, schema_entry, schema_value = next(values) + assert schema_entry.name == "/.schema/protobuf:Reading" + assert schema_value == "int32 i; int32 j" + with pytest.raises(ValueError, match=r"/reading.*struct:Reading.*4"): + next(values) + + +def test_iter_auto_tracks_entry_lifecycle_and_omits_controls(tmp_path): + path = tmp_path / "lifecycle.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry_a = log.start("/a", "int64", "initial-a", 1) + entry_b = log.start("/b", "string", "initial-b", 2) + log.append_integer(entry_a, 10, 3) + log.append_string(entry_b, "first-b", 4) + log.set_metadata(entry_a, "updated-a", 5) + log.append_integer(entry_a, 11, 6) + log.finish(entry_a, 7) + log.append_raw(entry_a, b"after-finish", 8) + reused_entry_a = log.start("/a", "double", "reused-a", 9) + assert reused_entry_a == entry_a + log.append_double(reused_entry_a, 2.5, 10) + log.append_string(entry_b, "second-b", 11) + log.append_raw(999, b"orphan", 12) + + values = _read_auto(path) + + assert [value for _, _, value in values] == [ + 10, + "first-b", + 11, + b"after-finish", + 2.5, + "second-b", + b"orphan", + ] + assert [start.name if start else None for _, start, _ in values] == [ + "/a", + "/b", + "/a", + None, + "/a", + "/b", + None, + ] + assert [start.type if start else None for _, start, _ in values] == [ + "int64", + "string", + "int64", + None, + "double", + "string", + None, + ] + assert [start.metadata if start else None for _, start, _ in values] == [ + "initial-a", + "initial-b", + "initial-a", + None, + "reused-a", + "initial-b", + None, + ] + + +@pytest.fixture +def log_path(tmp_path): + path = tmp_path / "reader.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + wpilog.IntegerLogEntry(log, "/value").append(42, 10) + return path + + +def test_normal_reader_iteration_is_unchanged(log_path): + reader = wpilog.DataLogReader(str(log_path)) + values = list(reader) + + assert reader.is_valid() + assert values + assert all(isinstance(record, wpilog.DataLogRecord) for record in values) + + +def test_iter_auto_is_single_pass_and_keeps_temporary_reader_alive(log_path): + reader = wpilog.DataLogReader(str(log_path)) + reader_ref = weakref.ref(reader) + values = reader.iter_auto() + values_ref = weakref.ref(values) + + [(record, start, decoded)] = list(values) + assert list(values) == [] + del reader, values + gc.collect() + allocations = [bytearray([index % 251]) * 4096 for index in range(1024)] + del allocations + gc.collect() + + assert reader_ref() is not None + assert values_ref() is None + assert isinstance(record, wpilog.DataLogRecord) + assert record.get_timestamp() == 10 + assert record.get_raw() == b"*\x00\x00\x00\x00\x00\x00\x00" + assert (start.name, start.type, start.metadata) == ("/value", "int64", "") + assert decoded == 42 + + +def test_iter_auto_temporary_reader_results_survive_exhaustion(log_path): + def read_temporary(): + reader = wpilog.DataLogReader(str(log_path)) + reader_ref = weakref.ref(reader) + return list(reader.iter_auto()), reader_ref + + [(record, start, decoded)], reader_ref = read_temporary() + gc.collect() + allocations = [bytearray([index % 251]) * 4096 for index in range(1024)] + del allocations + gc.collect() + + assert reader_ref() is not None + assert record.get_timestamp() == 10 + assert record.get_raw() == b"*\x00\x00\x00\x00\x00\x00\x00" + assert (start.name, start.type, start.metadata) == ("/value", "int64", "") + assert decoded == 42 + + +@wpistruct.make_wpistruct(name="Reading") +@dataclasses.dataclass +class _OtherReading: + value: wpistruct.uint8 = 0 + + +def test_iter_auto_validates_supplied_types_at_method_call(log_path): + reader = wpilog.DataLogReader(str(log_path)) + + with pytest.raises(ValueError, match="duplicate supplied struct type Reading"): + reader.iter_auto(Reading, _OtherReading) + + +def test_iter_auto_does_not_consume_records_at_method_call(tmp_path): + path = tmp_path / "lazy.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry = log.start("/invalid", "int64", "", 1) + log.append_raw(entry, b"", 2) + + values = wpilog.DataLogReader(str(path)).iter_auto() + + with pytest.raises(TypeError, match="not an integer"): + next(values) diff --git a/subprojects/robotpy-wpilog/tests/test_wpilog.py b/subprojects/robotpy-wpilog/tests/test_wpilog.py index 6e8139b9d..75ea811a9 100644 --- a/subprojects/robotpy-wpilog/tests/test_wpilog.py +++ b/subprojects/robotpy-wpilog/tests/test_wpilog.py @@ -1,4 +1,6 @@ import dataclasses +import gc +import weakref from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path @@ -42,6 +44,108 @@ def test_datalog_writer_context_manager_stops_writer(tmp_path: Path): assert path.stat().st_size == 54 +def _collect_and_churn_allocator(): + gc.collect() + allocations = [bytearray([index % 251]) * 4096 for index in range(1024)] + assert sum(allocation[0] for allocation in allocations) > 0 + del allocations + gc.collect() + + +def test_reader_private_stable_iterator_copies_records(tmp_path: Path): + path = tmp_path / "stable-records.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry = log.start("/value", "raw", "metadata", 1) + log.append_raw(entry, b"first", 2) + log.append_raw(entry, b"second", 3) + + reader = wpilog.DataLogReader(str(path)) + reader_ref = weakref.ref(reader) + records = iter(reader._iter_stable()) + iterator_ref = weakref.ref(records) + start_record = next(records) + start_data = start_record.get_start_data() + start_record_ref = weakref.ref(start_record) + first = next(records) + first_state = (first.get_entry(), first.get_timestamp(), first.get_raw()) + second = next(records) + with pytest.raises(StopIteration): + next(records) + + del reader, records, start_record + _collect_and_churn_allocator() + + assert reader_ref() is not None + assert iterator_ref() is not None + assert start_record_ref() is not None + assert start_data.entry == entry + assert (start_data.name, start_data.type, start_data.metadata) == ( + "/value", + "raw", + "metadata", + ) + assert first is not second + assert first_state == (entry, 2, b"first") + assert (first.get_entry(), first.get_timestamp(), first.get_raw()) == first_state + assert (second.get_entry(), second.get_timestamp(), second.get_raw()) == ( + entry, + 3, + b"second", + ) + + +def test_temporary_reader_stable_results_outlive_exhausted_iterator(tmp_path: Path): + path = tmp_path / "temporary-stable-records.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry = log.start("/temporary", "raw", "temporary-metadata", 11) + log.append_raw(entry, b"temporary-payload", 12) + + def read_temporary(): + reader = wpilog.DataLogReader(str(path)) + reader_ref = weakref.ref(reader) + return list(reader._iter_stable()), reader_ref + + records, reader_ref = read_temporary() + start_data = records[0].get_start_data() + data_record = records[1] + del records + _collect_and_churn_allocator() + + assert reader_ref() is not None + assert data_record.get_timestamp() == 12 + assert data_record.get_raw() == b"temporary-payload" + assert start_data.entry == entry + assert (start_data.name, start_data.type, start_data.metadata) == ( + "/temporary", + "raw", + "temporary-metadata", + ) + + +def test_metadata_record_data_keeps_source_record_alive(tmp_path: Path): + path = tmp_path / "stable-metadata-record.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry = log.start("/value", "raw", "initial", 1) + log.set_metadata(entry, "updated", 2) + + reader = wpilog.DataLogReader(str(path)) + reader_ref = weakref.ref(reader) + records = iter(reader._iter_stable()) + iterator_ref = weakref.ref(records) + next(records) + metadata_record = next(records) + metadata = metadata_record.get_set_metadata_data() + metadata_record_ref = weakref.ref(metadata_record) + del reader, records, metadata_record + _collect_and_churn_allocator() + + assert reader_ref() is not None + assert iterator_ref() is not None + assert metadata_record_ref() is not None + assert metadata.entry == entry + assert metadata.metadata == "updated" + + def test_simple_int(tmp_path: Path): with _log(tmp_path, "simple-int.wpilog", 54) as log: entry = log.start("test", "int64", "", 1) diff --git a/subprojects/robotpy-wpilog/wpilog/_datalog.py b/subprojects/robotpy-wpilog/wpilog/_datalog.py new file mode 100644 index 000000000..14229fbc9 --- /dev/null +++ b/subprojects/robotpy-wpilog/wpilog/_datalog.py @@ -0,0 +1,274 @@ +from collections import deque +from collections.abc import Iterator +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from wpiutil import wpistruct +from wpiutil.wpistruct._schema import ( + InvalidStructSchema, + StructTypeRegistry, + _UnresolvedStructSchema, +) + +if TYPE_CHECKING: + from ._wpilog import DataLogReader, DataLogRecord, StartRecordData + + +_SCHEMA_PREFIX = "/.schema/struct:" +_STRUCT_PREFIX = "struct:" +_UNCACHED = object() + + +@dataclass +class _DataEvent: + record: object + entry: object + schema_value: object = _UNCACHED + schema_error: Exception | None = None + + +_GETTERS = { + "boolean": "get_boolean", + "int64": "get_integer", + "float": "get_float", + "double": "get_double", + "string": "get_string", + "json": "get_string", + "boolean[]": "get_boolean_array", + "int64[]": "get_integer_array", + "float[]": "get_float_array", + "double[]": "get_double_array", + "string[]": "get_string_array", + "raw": "get_raw", +} + + +def _iter_auto( + reader: "DataLogReader", struct_types: tuple[type, ...] +) -> Iterator[tuple["DataLogRecord", "StartRecordData | None", object]]: + registry = StructTypeRegistry(struct_types) + return _iter_records(reader, registry) + + +def _iter_records(reader, registry): + records = iter(reader._iter_stable()) + entries = {} + queued = deque() + pending = {} + pending_types = {} + deferred_types = {} + while True: + try: + event = queued.popleft() if queued else _next_data_event(records, entries) + except StopIteration: + return + + required = _missing_struct_type(event.entry, registry) + if required is not None: + _lookahead( + required, + event, + records, + entries, + queued, + pending, + pending_types, + deferred_types, + registry, + ) + yield event.record, event.entry, _decode_event(event, registry) + + +def _next_data_event(records, entries): + while True: + record = next(records) + if record.is_start(): + start = record.get_start_data() + entries[start.entry] = start + continue + if record.is_finish(): + entries.pop(record.get_finish_entry(), None) + continue + if record.is_set_metadata() or record.is_control(): + continue + return _DataEvent(record, entries.get(record.get_entry())) + + +def _missing_struct_type(entry, registry): + if entry is None: + return None + struct_info = _struct_type_name(entry.type) + if struct_info is None: + return None + type_name, _ = struct_info + return type_name if registry.get(type_name) is None else None + + +def _schema_event_type_name(event): + if event.entry is None or event.entry.type != "structschema": + return None + return _schema_type_name(event.entry.name) + + +def _prepare_schema(event, registry): + if event.schema_value is not _UNCACHED or event.schema_error is not None: + return None, None + + type_name = _schema_event_type_name(event) + try: + schema = event.record.get_string() + event.schema_value = registry.add_schema(type_name, schema) + except UnicodeDecodeError as exc: + event.schema_error = exc + except InvalidStructSchema: + event.schema_value = schema + except _UnresolvedStructSchema as exc: + return None, exc.type_name + except ValueError as exc: + event.schema_error = exc + else: + return type_name, None + return None, None + + +def _prepare_ordered_schema(event, pending, pending_types, deferred_types, registry): + type_name = _schema_event_type_name(event) + if type_name in pending_types: + deferred_types.setdefault(type_name, deque()).append(event) + return None + + registered, missing = _prepare_schema(event, registry) + if missing is not None: + pending.setdefault(missing, []).append(event) + pending_types[type_name] = event + return registered + + +def _prepare_deferred_schemas( + type_name, pending, pending_types, deferred_types, released, registry +): + deferred = deferred_types.pop(type_name, ()) + while deferred: + event = deferred.popleft() + registered, missing = _prepare_schema(event, registry) + if missing is not None: + pending.setdefault(missing, []).append(event) + pending_types[type_name] = event + if deferred: + deferred_types[type_name] = deferred + return + if registered is not None: + released.append(registered) + + +def _retry_pending(registered_type, pending, pending_types, deferred_types, registry): + released = deque((registered_type,)) + while released: + dependency = released.popleft() + for event in pending.pop(dependency, ()): + registered, missing = _prepare_schema(event, registry) + if missing is not None: + pending.setdefault(missing, []).append(event) + continue + + type_name = _schema_event_type_name(event) + pending_types.pop(type_name) + if registered is not None: + released.append(registered) + _prepare_deferred_schemas( + type_name, + pending, + pending_types, + deferred_types, + released, + registry, + ) + + +def _lookahead( + required_type, + blocked, + records, + entries, + queued, + pending, + pending_types, + deferred_types, + registry, +): + while True: + try: + event = _next_data_event(records, entries) + except StopIteration: + _decode_value(blocked.record, blocked.entry, registry) + raise AssertionError("unreachable") + + queued.append(event) + if _schema_event_type_name(event) is None: + continue + + registered = _prepare_ordered_schema( + event, pending, pending_types, deferred_types, registry + ) + if registered is not None: + _retry_pending(registered, pending, pending_types, deferred_types, registry) + + if registry.get(required_type) is not None: + return + + +def _decode_event(event, registry): + if event.schema_error is not None: + raise event.schema_error + if event.schema_value is not _UNCACHED: + return event.schema_value + if event.entry is None: + return event.record.get_raw() + return _decode_value(event.record, event.entry, registry) + + +def _schema_type_name(entry_name): + _, marker, type_name = entry_name.rpartition(_SCHEMA_PREFIX) + if not marker or not type_name: + return None + return type_name + + +def _struct_type_name(entry_type): + if not entry_type.startswith(_STRUCT_PREFIX): + return None + name = entry_type[len(_STRUCT_PREFIX) :] + is_array = name.endswith("[]") + return (name[:-2] if is_array else name), is_array + + +def _decode_value(record, entry, registry): + getter = _GETTERS.get(entry.type) + if getter is not None: + return getattr(record, getter)() + + if entry.type == "structschema": + schema = record.get_string() + type_name = _schema_type_name(entry.name) + if type_name is None: + return schema + try: + return registry.add_schema(type_name, schema) + except InvalidStructSchema: + return schema + + struct_info = _struct_type_name(entry.type) + if struct_info is not None: + type_name, is_array = struct_info + struct_type = registry.get(type_name) + if struct_type is None: + raise ValueError( + f"cannot decode entry {entry.name!r} with type {entry.type!r} " + f"at timestamp {record.get_timestamp()}: struct type " + f"{type_name!r} is not registered" + ) + if is_array: + return wpistruct.unpack_array(struct_type, record.get_raw()) + return wpistruct.unpack(struct_type, record.get_raw()) + + return record.get_raw() diff --git a/subprojects/robotpy-wpimath/tests/geometry/test_datalog_struct.py b/subprojects/robotpy-wpimath/tests/geometry/test_datalog_struct.py new file mode 100644 index 000000000..8887858e3 --- /dev/null +++ b/subprojects/robotpy-wpimath/tests/geometry/test_datalog_struct.py @@ -0,0 +1,64 @@ +from pathlib import Path + +import wpilog +from wpimath import Pose2d, Rotation2d +from wpiutil import wpistruct + + +def test_iter_auto_supplied_native_pose2d(tmp_path: Path): + pose = Pose2d(1.0, 2.0, Rotation2d()) + path = tmp_path / "native-struct.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + wpilog.StructLogEntry(log, "/pose", Pose2d).append(pose, 10) + + decoded = [ + value + for _, entry, value in wpilog.DataLogReader(str(path)).iter_auto(Pose2d) + if entry is not None and entry.type == "struct:Pose2d" + ] + assert decoded == [pose] + + +def test_iter_auto_generates_native_pose2d_value_before_schema(tmp_path: Path): + first_pose = Pose2d(1.25, -2.5, Rotation2d(0.5)) + second_pose = Pose2d(-3.0, 4.5, Rotation2d(-0.75)) + path = tmp_path / "native-pose-before-schema.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + pose_entry = log.start("/pose", "struct:Pose2d", "", 1) + log.append_raw(pose_entry, wpistruct.pack(first_pose), 2) + wpistruct.for_each_nested( + Pose2d, + lambda type_string, schema: log.add_schema( + type_string, "structschema", schema + ), + ) + log.append_raw(pose_entry, wpistruct.pack(second_pose), 6) + + values = list(wpilog.DataLogReader(str(path)).iter_auto()) + + assert [entry.type for _, entry, _ in values] == [ + "struct:Pose2d", + "structschema", + "structschema", + "structschema", + "struct:Pose2d", + ] + first, generated_translation, generated_rotation, generated_pose, second = [ + value for _, _, value in values + ] + assert type(first) is generated_pose + assert type(second) is generated_pose + assert type(first.translation) is generated_translation + assert type(first.rotation) is generated_rotation + assert type(second.translation) is generated_translation + assert type(second.rotation) is generated_rotation + assert (first.translation.x, first.translation.y, first.rotation.value) == ( + 1.25, + -2.5, + 0.5, + ) + assert (second.translation.x, second.translation.y, second.rotation.value) == ( + -3.0, + 4.5, + -0.75, + ) diff --git a/subprojects/robotpy-wpiutil/meson.build b/subprojects/robotpy-wpiutil/meson.build index daed8c41f..ef5e9125b 100644 --- a/subprojects/robotpy-wpiutil/meson.build +++ b/subprojects/robotpy-wpiutil/meson.build @@ -11,6 +11,7 @@ wpiutil_sources += files( 'wpiutil/src/timestamp.cpp', 'wpiutil/src/usagereporting.cpp', 'wpiutil/src/wpistruct/wpystruct_fns.cpp', + 'wpiutil/src/wpistruct/wpystruct_schema.cpp', ) subdir('semiwrap/modules') diff --git a/subprojects/robotpy-wpiutil/pyproject.in.toml b/subprojects/robotpy-wpiutil/pyproject.in.toml index 471a96deb..f09593e95 100644 --- a/subprojects/robotpy-wpiutil/pyproject.in.toml +++ b/subprojects/robotpy-wpiutil/pyproject.in.toml @@ -85,6 +85,7 @@ Alert = "wpi/util/Alert.hpp" UsageReporting = "wpi/util/UsageReporting.hpp" WPyStruct = "src/wpistruct/wpystruct_fns.h" +WPyStructSchema = "src/wpistruct/wpystruct_schema.h" [tool.semiwrap.export_type_casters.wpiutil-casters] pypackage = "wpiutil" diff --git a/subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml b/subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml new file mode 100644 index 000000000..0ede44b52 --- /dev/null +++ b/subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml @@ -0,0 +1,69 @@ +defaults: + subpackage: _schema + +functions: + PackSchema: + no_release_gil: true + UnpackSchema: + no_release_gil: true + +classes: + wpy::structs::SchemaFieldDescriptor: + attributes: + name: + access: readonly + type: + access: readonly + size: + access: readonly + offset: + access: readonly + arraySize: + access: readonly + bitWidth: + access: readonly + bitShift: + access: readonly + bitMask: + access: readonly + enumValues: + access: readonly + structName: + access: readonly + isArray: + access: readonly + isBitField: + access: readonly + isEnum: + access: readonly + wpy::structs::SchemaDescriptor: + methods: + SchemaDescriptor: + ignore: true + GetName: + no_release_gil: true + GetSchema: + no_release_gil: true + IsValid: + no_release_gil: true + GetSize: + no_release_gil: true + GetFields: + no_release_gil: true + wpy::structs::SchemaDatabase: + methods: + SchemaDatabase: + Add: + no_release_gil: true + Stage: + no_release_gil: true + Find: + no_release_gil: true + +inline_code: | + cls_SchemaDescriptor + .def_property_readonly("name", &wpy::structs::SchemaDescriptor::GetName) + .def_property_readonly("schema", &wpy::structs::SchemaDescriptor::GetSchema) + .def_property_readonly("is_valid", &wpy::structs::SchemaDescriptor::IsValid) + .def_property_readonly("size", &wpy::structs::SchemaDescriptor::GetSize) + .def_property_readonly("fields", &wpy::structs::SchemaDescriptor::GetFields); diff --git a/subprojects/robotpy-wpiutil/tests/test_schema_bridge.py b/subprojects/robotpy-wpiutil/tests/test_schema_bridge.py new file mode 100644 index 000000000..ca824b43b --- /dev/null +++ b/subprojects/robotpy-wpiutil/tests/test_schema_bridge.py @@ -0,0 +1,562 @@ +import gc +import math +import subprocess +import sys + +import pytest + +from wpiutil._wpiutil._schema import SchemaDatabase, pack_schema, unpack_schema + + +def test_schema_descriptor_metadata(): + db = SchemaDatabase() + desc = db.add("Packet", "int32 count; uint16 flags:3") + + assert desc.name == "Packet" + assert desc.schema == "int32 count; uint16 flags:3" + assert desc.is_valid + assert desc.size == 6 + assert [field.name for field in desc.fields] == ["count", "flags"] + assert desc.fields[0].type == "int32" + assert desc.fields[0].offset == 0 + assert desc.fields[1].offset == 4 + assert desc.fields[1].bit_width == 3 + assert desc.fields[1].bit_shift == 0 + assert desc.fields[1].bit_mask == 0x7 + + +def test_schema_descriptor_nested_delayed_validity(): + db = SchemaDatabase() + outer = db.add("Outer", "Inner value") + assert not outer.is_valid + with pytest.raises(ValueError, match="descriptor Outer is not valid"): + _ = outer.size + + db.add("Inner", "int32 value") + assert outer.is_valid + assert outer.size == 4 + assert outer.fields[0].struct_name == "Inner" + + +def test_schema_descriptor_parse_error(): + db = SchemaDatabase() + with pytest.raises(ValueError, match="expected identifier"): + db.add("Bad", "int32 [2]") + + +def test_schema_descriptor_retains_database(): + desc = SchemaDatabase().add("Value", "uint8 value") + gc.collect() + assert desc.size == 1 + assert desc.fields[0].name == "value" + + +def test_schema_database_find(): + db = SchemaDatabase() + assert db.find("Value") is None + + added = db.add("Value", "uint8 value") + found = db.find("Value") + + assert found is not None + assert found.name == added.name + assert found.schema == added.schema + assert found.size == added.size + + +def test_schema_descriptor_preserves_declaration_shape_metadata(): + desc = SchemaDatabase().add( + "Shapes", + "uint8 scalar; uint8 singleton[1]; uint8 full_width:8; " + "enum {} uint8 empty_mode", + ) + + scalar, singleton, full_width, empty_mode = desc.fields + assert not scalar.is_array + assert not scalar.is_bit_field + assert not scalar.is_enum + assert singleton.is_array + assert not singleton.is_bit_field + assert not singleton.is_enum + assert not full_width.is_array + assert full_width.is_bit_field + assert not full_width.is_enum + assert not empty_mode.is_array + assert not empty_mode.is_bit_field + assert empty_mode.is_enum + + +def test_schema_database_stages_without_mutating_source(): + source = SchemaDatabase() + source.add("First", "uint8 value") + + staged = source.stage("Second", "First nested") + + assert source.find("Second") is None + assert staged.find("First").size == 1 + assert staged.find("Second").size == 1 + + duplicate_stage = source.stage("First", " uint8 value; ") + duplicate_stage.add("Third", "uint16 value") + assert source.find("Third") is None + assert duplicate_stage.find("Third").size == 2 + + +def test_schema_database_stage_rejects_contextually_different_bool_bitfield(): + database = SchemaDatabase() + database.add("Packet", "int16 prefix:2; bool value") + + with pytest.raises(ValueError, match="conflicting schema for Packet"): + database.stage("Packet", "int16 prefix:2; bool value:1") + + +def test_schema_database_stage_rejects_non_full_width_integer_bitfield(): + database = SchemaDatabase() + database.add("Packet", "uint8 value") + + with pytest.raises(ValueError, match="conflicting schema for Packet"): + database.stage("Packet", "uint8 value:7") + + +@pytest.mark.parametrize( + ("existing_schema", "candidate_schema", "attribute", "expected"), + [ + ("uint8 value", "uint8 value[1]", "is_array", True), + ("uint8 value[1]", "uint8 value", "is_array", False), + ("uint8 value", "uint8 value:8", "is_bit_field", True), + ("int16 value", "int16 value:16", "is_bit_field", True), + ("uint32 value:32", "uint32 value", "is_bit_field", False), + ("int64 value", "int64 value:64", "is_bit_field", True), + ("uint8 value", "enum {} uint8 value", "is_enum", True), + ], +) +def test_equivalent_stage_uses_candidate_declaration_shape( + existing_schema, candidate_schema, attribute, expected +): + database = SchemaDatabase() + source = database.add("Packet", existing_schema) + + staged = database.stage("Packet", candidate_schema) + candidate = staged.find("Packet") + + assert candidate.schema == candidate_schema + assert source.schema == existing_schema + assert database.find("Packet").schema == existing_schema + assert getattr(candidate.fields[0], attribute) is expected + assert getattr(source.fields[0], attribute) is not expected + assert getattr(database.find("Packet").fields[0], attribute) is not expected + + +def test_schema_descriptor_arrays_chars_and_enums(): + db = SchemaDatabase() + desc = db.add( + "Complete", + "char letter; char text[4]; int16 samples[3]; " "enum {OFF=0, ON=2} uint8 mode", + ) + + assert desc.size == 12 + assert [field.name for field in desc.fields] == [ + "letter", + "text", + "samples", + "mode", + ] + assert [field.type for field in desc.fields] == [ + "char", + "char", + "int16", + "uint8", + ] + assert [field.offset for field in desc.fields] == [0, 1, 5, 11] + assert [field.size for field in desc.fields] == [1, 1, 2, 1] + assert [field.array_size for field in desc.fields] == [1, 4, 3, 1] + assert desc.fields[3].enum_values == [("OFF", 0), ("ON", 2)] + + +@pytest.mark.parametrize( + ("schema_type", "canonical_type", "size"), + [("float32", "float", 4), ("float64", "double", 8)], +) +def test_schema_descriptor_primitive_aliases(schema_type, canonical_type, size): + db = SchemaDatabase() + desc = db.add("Value", f"{schema_type} value") + + assert desc.size == size + assert desc.fields[0].type == canonical_type + assert desc.fields[0].size == size + + +@pytest.mark.parametrize( + ("schema", "error"), + [ + ("char value:1", "type char cannot be bitfield"), + ("int8 value:9", "bit width 9 exceeds type size"), + ("bool value:2", "bit width must be 1 for bool type"), + ("Recursive value", "recursive struct reference"), + ("int8 value; int16 value", "duplicate field value"), + ], +) +def test_schema_descriptor_semantic_validation_errors(schema, error): + db = SchemaDatabase() + + with pytest.raises(ValueError, match=error): + db.add("Recursive", schema) + + +def test_schema_descriptor_duplicate_and_conflicting_definitions(): + db = SchemaDatabase() + original = db.add("Value", "float value") + + duplicate = db.add("Value", "float32 value") + assert duplicate.schema == original.schema + assert duplicate.size == original.size + + with pytest.raises(ValueError, match="conflicting schema for Value"): + db.add("Value", "double value") + + assert db.find("Value").schema == "float value" + assert db.find("Value").size == 4 + + +def test_failed_semantic_add_does_not_create_descriptor(): + db = SchemaDatabase() + + with pytest.raises(ValueError, match="duplicate field value"): + db.add("Bad", "int8 value; int16 value") + + assert db.find("Bad") is None + recovered = db.add("Bad", "int8 value") + assert recovered.is_valid + assert recovered.size == 1 + + +def test_failed_placeholder_completion_is_transactional(): + db = SchemaDatabase() + outer = db.add("Outer", "Inner value") + inner_placeholder = db.find("Inner") + assert inner_placeholder is not None + assert not inner_placeholder.is_valid + + with pytest.raises(ValueError, match="circular struct reference"): + db.add("Inner", "Outer value") + + assert not outer.is_valid + assert not inner_placeholder.is_valid + assert inner_placeholder.schema == "" + + inner = db.add("Inner", "int32 value") + assert inner.is_valid + assert inner.size == 4 + assert outer.is_valid + assert outer.size == 4 + + +def test_schema_layout_overflow_is_rejected_before_publication(): + db = SchemaDatabase() + + with pytest.raises( + ValueError, + match=( + r"unsafe schema layout for Overflow: field values storage extent " + r"exceeds platform limits" + ), + ): + db.add("Overflow", "uint64 values[2305843009213693952]") + + assert db.find("Overflow") is None + recovered = db.add("Overflow", "uint8 value") + assert recovered.is_valid + assert recovered.size == 1 + + +def test_nested_schema_layout_overflow_is_rejected_transactionally(): + db = SchemaDatabase() + outer = db.add("Outer", "Inner values[2305843009213693952]") + inner_placeholder = db.find("Inner") + assert inner_placeholder is not None + assert not outer.is_valid + assert not inner_placeholder.is_valid + + with pytest.raises( + ValueError, + match=( + r"unsafe schema layout for Outer: field values storage extent " + r"exceeds platform limits" + ), + ): + db.add("Inner", "uint64 value") + + assert not outer.is_valid + assert not inner_placeholder.is_valid + assert inner_placeholder.schema == "" + + inner = db.add("Inner", "") + assert inner.is_valid + assert inner.size == 0 + assert outer.is_valid + assert outer.size == 0 + + +@pytest.mark.parametrize( + ("schema", "value", "encoded"), + [ + ("bool value", True, b"\x01"), + ("int8 value", -2, b"\xfe"), + ("uint16 value", 0x1234, b"\x34\x12"), + ("int32 value", -3, b"\xfd\xff\xff\xff"), + ("float value", 1.5, b"\x00\x00\xc0?"), + ("double value", 1.5, b"\x00\x00\x00\x00\x00\x00\xf8?"), + ], +) +def test_schema_primitive_round_trip(schema, value, encoded): + desc = SchemaDatabase().add("Value", schema) + assert pack_schema(desc, (value,)) == encoded + assert unpack_schema(desc, encoded) == (value,) + + +def test_schema_array_and_nested_round_trip(): + db = SchemaDatabase() + db.add("Inner", "int16 value") + outer = db.add("Outer", "uint8 samples[2]; Inner inner") + encoded = pack_schema(outer, ((1, 2), b"\xfe\xff")) + assert encoded == b"\x01\x02\xfe\xff" + assert unpack_schema(outer, encoded) == ((1, 2), b"\xfe\xff") + + +def test_schema_non_char_array_accepts_byte_sequences(): + desc = SchemaDatabase().add("Samples", "uint8 samples[2]") + + assert pack_schema(desc, (b"\x01\x02",)) == b"\x01\x02" + assert pack_schema(desc, (bytearray(b"\x03\x04"),)) == b"\x03\x04" + + +def test_schema_singleton_array_uses_wpilib_scalar_semantics(): + db = SchemaDatabase() + desc = db.add("Packet", "uint8 samples[1]") + + assert desc.schema == "uint8 samples[1]" + assert desc.fields[0].array_size == 1 + assert pack_schema(desc, (7,)) == b"\x07" + assert unpack_schema(desc, b"\x08") == (8,) + + with pytest.raises(TypeError, match="samples.*must be an integer"): + pack_schema(desc, ((7,),)) + + equivalent = db.add("Packet", "uint8 samples") + assert equivalent.schema == "uint8 samples[1]" + + +def test_schema_nested_array_unpacks_exact_size_bytes(): + db = SchemaDatabase() + db.add("Inner", "uint16 value") + outer = db.add("Outer", "Inner nested[2]") + + assert unpack_schema(outer, b"\x01\x00\x02\x00") == ((b"\x01\x00", b"\x02\x00"),) + + +def test_schema_bitfield_layout_and_sign_extension(): + desc = SchemaDatabase().add("Bits", "int16 signed:3; bool ready:1; uint16 count:4") + encoded = pack_schema(desc, (-1, True, 9)) + assert encoded == b"\x9f\x00" + assert unpack_schema(desc, encoded) == (-1, True, 9) + + +def test_schema_enum_is_an_integer_at_native_boundary(): + desc = SchemaDatabase().add("Mode", "enum {OFF=0,AUTO=1} uint8 mode") + assert pack_schema(desc, (1,)) == b"\x01" + assert unpack_schema(desc, b"\x07") == (7,) + assert desc.fields[0].enum_values == [("OFF", 0), ("AUTO", 1)] + + +def test_schema_char_array_preserves_embedded_nul(): + desc = SchemaDatabase().add("Text", "char text[5]") + assert pack_schema(desc, ("ab\0c",)) == b"ab\0c\0" + assert unpack_schema(desc, b"ab\0c\0") == ("ab\0c",) + + +def test_schema_char_array_rejects_utf8_truncation(): + desc = SchemaDatabase().add("Text", "char text[2]") + with pytest.raises(ValueError, match="text.*2 bytes"): + pack_schema(desc, ("a\u1234",)) + + +def test_schema_pack_pins_descriptor_during_sequence_reentrancy(): + script = """ +from wpiutil._wpiutil._schema import SchemaDatabase, pack_schema + + +class MutatingValues: + def __init__(self, db): + self.db = db + self.mutated = False + + def __len__(self): + if not self.mutated: + self.mutated = True + self.db.add("Other", "uint64 a; uint64 b; uint64 c; uint64 d") + return 1 + + def __getitem__(self, index): + if index == 0: + return 7 + raise IndexError + + +db = SchemaDatabase() +desc = db.add("Value", "uint8 value") +assert pack_schema(desc, MutatingValues(db)) == b"\\x07" +assert db.find("Other").is_valid +""" + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + timeout=10, + ) + + assert result.returncode == 0, result.stderr + + +def test_schema_codec_validation(): + desc = SchemaDatabase().add("Value", "uint8 value; int8 nibble:4") + + with pytest.raises(ValueError, match="expected 2 fields"): + pack_schema(desc, (1,)) + with pytest.raises(ValueError, match="value.*0.*255"): + pack_schema(desc, (256, 0)) + with pytest.raises(ValueError, match="nibble.*-8.*7"): + pack_schema(desc, (1, 8)) + with pytest.raises(ValueError, match="buffer must be 2 bytes"): + unpack_schema(desc, b"\x00") + + +@pytest.mark.parametrize( + ("schema", "value", "bounds"), + [ + ("int8 value", 128, r"-128.*127"), + ("uint8 value", 256, r"0.*255"), + ], +) +def test_schema_integer_subclass_cannot_bypass_range_validation(schema, value, bounds): + class LyingInt(int): + def __lt__(self, other): + return False + + def __gt__(self, other): + return False + + desc = SchemaDatabase().add("Value", schema) + + with pytest.raises(ValueError, match=rf"value.*{bounds}"): + pack_schema(desc, (LyingInt(value),)) + + +@pytest.mark.parametrize( + ("schema", "below_minimum", "above_maximum"), + [ + ("int8 value", -(2**7) - 1, 2**7), + ("int16 value", -(2**15) - 1, 2**15), + ("int32 value", -(2**31) - 1, 2**31), + ("int64 value", -(2**63) - 1, 2**63), + ("uint8 value", -1, 2**8), + ("uint16 value", -1, 2**16), + ("uint32 value", -1, 2**32), + ("uint64 value", -1, 2**64), + ], +) +def test_schema_integer_rejects_one_past_limits(schema, below_minimum, above_maximum): + desc = SchemaDatabase().add("Value", schema) + + with pytest.raises(ValueError, match="value.*must be between"): + pack_schema(desc, (below_minimum,)) + with pytest.raises(ValueError, match="value.*must be between"): + pack_schema(desc, (above_maximum,)) + + +@pytest.mark.parametrize( + ("schema", "minimum", "maximum"), + [ + ("int8 value:4", -8, 7), + ("uint64 value:63", 0, 2**63 - 1), + ], +) +def test_schema_bitfield_enforces_exact_integer_limits(schema, minimum, maximum): + desc = SchemaDatabase().add("Value", schema) + + for value in (minimum, maximum): + assert unpack_schema(desc, pack_schema(desc, (value,))) == (value,) + for value in (minimum - 1, maximum + 1): + with pytest.raises(ValueError, match="value.*must be between"): + pack_schema(desc, (value,)) + + +@pytest.mark.parametrize( + ("schema", "minimum", "maximum"), + [ + ("int8 value", -(2**7), 2**7 - 1), + ("int16 value", -(2**15), 2**15 - 1), + ("int32 value", -(2**31), 2**31 - 1), + ("int64 value", -(2**63), 2**63 - 1), + ("uint8 value", 0, 2**8 - 1), + ("uint16 value", 0, 2**16 - 1), + ("uint32 value", 0, 2**32 - 1), + ("uint64 value", 0, 2**64 - 1), + ], +) +def test_schema_integer_limits(schema, minimum, maximum): + desc = SchemaDatabase().add("Value", schema) + for value in (minimum, maximum): + assert unpack_schema(desc, pack_schema(desc, (value,))) == (value,) + + +def test_schema_float_rejects_finite_float32_overflow(): + desc = SchemaDatabase().add("Value", "float value") + + float32_max = float.fromhex("0x1.fffffep+127") + assert pack_schema(desc, (float32_max,)) == b"\xff\xff\x7f\x7f" + assert pack_schema(desc, (-float32_max,)) == b"\xff\xff\x7f\xff" + + outside = math.nextafter(float32_max, math.inf) + for value in (outside, -outside, 1e300, -1e300): + with pytest.raises(ValueError, match="value.*float32 range"): + pack_schema(desc, (value,)) + + +@pytest.mark.parametrize( + ("value", "encoded"), + [ + (math.inf, b"\x00\x00\x80\x7f"), + (-math.inf, b"\x00\x00\x80\xff"), + ], +) +def test_schema_float_preserves_infinities(value, encoded): + desc = SchemaDatabase().add("Value", "float value") + + assert pack_schema(desc, (value,)) == encoded + assert unpack_schema(desc, encoded) == (value,) + + +def test_schema_float_preserves_nan(): + desc = SchemaDatabase().add("Value", "float value") + + (unpacked,) = unpack_schema(desc, pack_schema(desc, (math.nan,))) + assert math.isnan(unpacked) + + +@pytest.mark.parametrize( + ("schema", "values", "size"), + [ + ("int32 a:2; uint32 b:30", (-1, 100), 4), + ("int32 a:2; int16 b:2", (-1, -2), 6), + ("int8 a:4; int8 b:5", (-1, -2), 2), + ( + "int16 a:2; bool b:1; bool c:1; uint16 d:5", + (-1, True, False, 17), + 2, + ), + ], +) +def test_schema_bitfield_placement(schema, values, size): + desc = SchemaDatabase().add("Bits", schema) + assert desc.size == size + assert unpack_schema(desc, pack_schema(desc, values)) == values diff --git a/subprojects/robotpy-wpiutil/tests/test_struct.py b/subprojects/robotpy-wpiutil/tests/test_struct.py index 1fe2aa8d4..9421f7262 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct.py @@ -1,3 +1,4 @@ +import array import dataclasses import re @@ -62,6 +63,40 @@ def test_pack_into_err(): wpistruct.pack_into(module.ThingA(1), buf) +def test_pack_into_rejects_readonly_buffer(): + destination = b"\x00" + + with pytest.raises(BufferError, match="writable"): + wpistruct.pack_into(module.ThingA(1), destination) + + assert destination == b"\x00" + + +def test_pack_into_rejects_noncontiguous_buffer_without_mutation(): + backing = bytearray(b"\xaa\xbb") + destination = memoryview(backing)[::2] + + with pytest.raises(ValueError, match="buffer must be contiguous"): + wpistruct.pack_into(module.ThingA(1), destination) + + assert backing == b"\xaa\xbb" + + +@pytest.mark.parametrize( + "destination", + [ + bytearray(1), + memoryview(bytearray(1)), + array.array("b", [0]), + array.array("B", [0]), + ], +) +def test_pack_into_accepts_contiguous_writable_byte_buffers(destination): + wpistruct.pack_into(module.ThingA(7), destination) + + assert bytes(destination) == b"\x07" + + def test_unpack(): assert wpistruct.unpack(module.ThingA, b"\x01") == module.ThingA(1) @@ -179,6 +214,24 @@ def test_user_unpack(): assert wpistruct.unpack(MyStruct, b"\x02\x00\x00\x00\x01\x00\x00\x60\x40") == v +@wpistruct.make_wpistruct +@dataclasses.dataclass +class Empty: + pass + + +def test_user_empty_struct_scalar_round_trip(): + value = Empty() + + assert wpistruct.pack(value) == b"" + assert wpistruct.unpack(Empty, b"") == value + + +def test_user_empty_struct_array_unpack_is_rejected(): + with pytest.raises(ValueError, match="cannot unpack an array of zero-size structs"): + wpistruct.unpack_array(Empty, b"") + + @wpistruct.make_wpistruct(name="SingleFieldStruct") @dataclasses.dataclass class SingleFieldStruct: diff --git a/subprojects/robotpy-wpiutil/tests/test_struct_annotations.py b/subprojects/robotpy-wpiutil/tests/test_struct_annotations.py new file mode 100644 index 000000000..46588e8f0 --- /dev/null +++ b/subprojects/robotpy-wpiutil/tests/test_struct_annotations.py @@ -0,0 +1,644 @@ +import dataclasses +import enum +from typing import Annotated + +import pytest + +from wpiutil import wpistruct + + +def test_char_marker(): + assert wpistruct.char("x") == "x" + assert wpistruct.char("\0") == "\0" + with pytest.raises(ValueError, match="exactly one UTF-8 byte"): + wpistruct.char("\u1234") + + +def test_metadata_marker_validation(): + assert wpistruct.CharArray(4).size == 4 + assert wpistruct.BitField(3).width == 3 + with pytest.raises(ValueError, match="positive"): + wpistruct.CharArray(0) + with pytest.raises(ValueError, match="positive"): + wpistruct.BitField(-1) + + +@wpistruct.make_wpistruct(name="Legacy") +@dataclasses.dataclass +class Legacy: + count: int + values: tuple[wpistruct.uint16, wpistruct.uint16] + + +def test_legacy_schema_and_bytes_remain_exact(): + assert wpistruct.get_schema(Legacy) == "int32 count; uint16 values[2]" + assert wpistruct.pack(Legacy(1, (2, 3))) == b"\x01\0\0\0\x02\0\x03\0" + assert wpistruct.unpack(Legacy, b"\x01\0\0\0\x02\0\x03\0") == Legacy(1, (2, 3)) + + +def test_legacy_singleton_tuple_remains_an_array(): + @wpistruct.make_wpistruct + @dataclasses.dataclass + class SingletonTuple: + value: tuple[wpistruct.uint8] + + value = SingletonTuple((7,)) + assert wpistruct.get_schema(SingletonTuple) == "uint8 value[1]" + assert wpistruct.pack(value) == b"\x07" + assert wpistruct.unpack(SingletonTuple, b"\x08") == SingletonTuple((8,)) + + +def test_legacy_annotated_metadata_uses_base_type(): + @wpistruct.make_wpistruct + @dataclasses.dataclass + class AnnotatedValue: + value: Annotated[int, "application metadata"] + + value = AnnotatedValue(7) + assert wpistruct.get_schema(AnnotatedValue) == "int32 value" + assert wpistruct.unpack(AnnotatedValue, wpistruct.pack(value)) == value + + +def test_legacy_tuple_element_annotated_metadata_uses_base_type(): + @wpistruct.make_wpistruct + @dataclasses.dataclass + class AnnotatedTuple: + value: tuple[Annotated[wpistruct.uint8, "application metadata"]] + + value = AnnotatedTuple((7,)) + assert wpistruct.get_schema(AnnotatedTuple) == "uint8 value[1]" + assert wpistruct.unpack(AnnotatedTuple, wpistruct.pack(value)) == value + + +def test_legacy_metadata_equality_is_not_evaluated(): + class ApplicationMetadata: + def __eq__(self, other): + raise AssertionError("application metadata equality was evaluated") + + @wpistruct.make_wpistruct + @dataclasses.dataclass + class AnnotatedValue: + value: Annotated[int, ApplicationMetadata()] + + value = AnnotatedValue(7) + assert wpistruct.unpack(AnnotatedValue, wpistruct.pack(value)) == value + + +def test_compile_failure_does_not_partially_decorate_class(): + from wpiutil.wpistruct._compiler import compile_wpistruct + + @dataclasses.dataclass + class InvalidSchema: + value: int + + with pytest.raises(ValueError, match="expected identifier"): + compile_wpistruct(InvalidSchema, "InvalidSchema", schema_override="int32 [2]") + + assert "WPIStruct" not in InvalidSchema.__dict__ + assert "__wpistruct_descriptor__" not in InvalidSchema.__dict__ + + +def test_compiler_attaches_parsed_layout_metadata(): + assert Legacy.__wpistruct_descriptor__ == wpistruct.StructLayout( + type_name="Legacy", + schema="int32 count; uint16 values[2]", + size=8, + fields=( + wpistruct.StructFieldLayout( + schema_name="count", + python_name="count", + type_name="int32", + offset=0, + size=4, + array_size=1, + bit_width=32, + bit_shift=0, + bit_mask=0xFFFFFFFF, + enum_values=(), + nested_type=None, + ), + wpistruct.StructFieldLayout( + schema_name="values", + python_name="values", + type_name="uint16", + offset=4, + size=2, + array_size=2, + bit_width=16, + bit_shift=0, + bit_mask=0xFFFF, + enum_values=(), + nested_type=None, + ), + ), + ) + + +def test_legacy_unicode_field_names_preserve_schema_bytes_and_layout(): + unicode_struct = dataclasses.make_dataclass( + "LegacyUnicode", + [ + ("é", wpistruct.int32), + ("π", wpistruct.uint16), + ("变量", bool), + ("aé", wpistruct.int8), + ], + ) + unicode_struct = wpistruct.make_wpistruct(name="LegacyUnicode")(unicode_struct) + value = unicode_struct(-2, 0x1234, True, -3) + encoded = b"\xfe\xff\xff\xff\x34\x12\x01\xfd" + + assert wpistruct.get_schema(unicode_struct) == ( + "int32 é; uint16 π; bool 变量; int8 aé" + ) + assert wpistruct.pack(value) == encoded + assert wpistruct.unpack(unicode_struct, encoded) == value + assert unicode_struct.__wpistruct_descriptor__.schema == ( + "int32 é; uint16 π; bool 变量; int8 aé" + ) + assert [ + (field.schema_name, field.python_name) + for field in unicode_struct.__wpistruct_descriptor__.fields + ] == [("é", "é"), ("π", "π"), ("变量", "变量"), ("aé", "aé")] + + +def test_nested_legacy_unicode_fields_preserve_public_behavior(): + inner = dataclasses.make_dataclass("UnicodeInner", [("变量", wpistruct.uint16)]) + inner = wpistruct.make_wpistruct(name="UnicodeInner")(inner) + outer = dataclasses.make_dataclass( + "UnicodeOuter", [("π", inner), ("aé", wpistruct.int8)] + ) + outer = wpistruct.make_wpistruct(name="UnicodeOuter")(outer) + value = outer(inner(0x1234), -2) + encoded = b"\x34\x12\xfe" + + assert wpistruct.get_schema(inner) == "uint16 变量" + assert wpistruct.get_schema(outer) == "UnicodeInner π; int8 aé" + assert wpistruct.pack(value) == encoded + assert wpistruct.unpack(outer, encoded) == value + assert outer.__wpistruct_descriptor__.schema == "UnicodeInner π; int8 aé" + assert [ + (field.schema_name, field.python_name) + for field in outer.__wpistruct_descriptor__.fields + ] == [("π", "π"), ("aé", "aé")] + + nested_schemas = [] + wpistruct.for_each_nested( + outer, + lambda type_name, schema: nested_schemas.append((type_name, schema)), + ) + assert nested_schemas == [ + ("struct:UnicodeInner", "uint16 变量"), + ("struct:UnicodeOuter", "UnicodeInner π; int8 aé"), + ] + + +class Mode(enum.IntEnum): + OFF = 0 + AUTO = 1 + DEFAULT = 1 + + +_hostile_missing_calls = [] + + +class HostileMissingMode(enum.IntEnum): + OFF = 0 + AUTO = 1 + + @classmethod + def _missing_(cls, value): + _hostile_missing_calls.append(value) + cls._member_map_["INJECTED"] = cls.AUTO + return cls.AUTO + + +@wpistruct.make_wpistruct(name="Packet") +@dataclasses.dataclass +class Packet: + initial: wpistruct.char + name: Annotated[str, wpistruct.CharArray(5)] + mode: Annotated[Mode, wpistruct.uint8] + + +def test_char_and_enum_schema_round_trip(): + value = Packet(wpistruct.char("A"), "ab\0c", Mode.AUTO) + assert wpistruct.get_schema(Packet) == ( + "char initial; char name[5]; " "enum {OFF=0,AUTO=1,DEFAULT=1} uint8 mode" + ) + assert wpistruct.pack(value) == b"Aab\0c\0\x01" + assert wpistruct.unpack(Packet, wpistruct.pack(value)) == value + + +def test_unknown_enum_value_is_typed_without_mutating_enum(): + before_members = dict(Mode.__members__) + before_values = dict(Mode._value2member_map_) + value = wpistruct.unpack(Packet, b"Aab\0c\0\x07") + assert isinstance(value.mode, Mode) + assert value.mode.name == "UNKNOWN_7" + assert value.mode.value == 7 + assert Mode.__members__ == before_members + assert Mode._value2member_map_ == before_values + assert list(Mode) == [Mode.OFF, Mode.AUTO] + + +@wpistruct.make_wpistruct +@dataclasses.dataclass +class EnumCache: + first: Annotated[Mode, wpistruct.uint8] + second: Annotated[Mode, wpistruct.uint8] + + +def test_unknown_enum_pseudo_members_are_cached_per_field(): + first = wpistruct.unpack(EnumCache, b"\x07\x07") + second = wpistruct.unpack(EnumCache, b"\x07\x07") + + assert first.first is second.first + assert first.second is second.second + assert first.first is not first.second + + +@wpistruct.make_wpistruct +@dataclasses.dataclass +class HostileMissingPacket: + mode: Annotated[HostileMissingMode, wpistruct.uint8] + + +def test_enum_unpack_does_not_call_missing_or_mutate_class_maps(): + _hostile_missing_calls.clear() + before_members = dict(HostileMissingMode.__members__) + before_values = dict(HostileMissingMode._value2member_map_) + + known = wpistruct.unpack(HostileMissingPacket, b"\x01") + first_unknown = wpistruct.unpack(HostileMissingPacket, b"\x07") + second_unknown = wpistruct.unpack(HostileMissingPacket, b"\x07") + + assert known.mode is HostileMissingMode.AUTO + assert first_unknown.mode is second_unknown.mode + assert first_unknown.mode.name == "UNKNOWN_7" + assert first_unknown.mode.value == 7 + assert _hostile_missing_calls == [] + assert HostileMissingMode.__members__ == before_members + assert HostileMissingMode._value2member_map_ == before_values + + +@wpistruct.make_wpistruct +@dataclasses.dataclass +class AuthoredSingletonArrays: + initial: wpistruct.char + samples: tuple[wpistruct.uint8] + modes: Annotated[tuple[Mode], wpistruct.uint8] + nested: tuple[Legacy] + + +def test_descriptor_codec_preserves_authored_singleton_tuple_semantics(): + value = AuthoredSingletonArrays( + wpistruct.char("A"), (7,), (Mode.AUTO,), (Legacy(2, (3, 4)),) + ) + + assert wpistruct.get_schema(AuthoredSingletonArrays) == ( + "char initial; uint8 samples[1]; " + "enum {OFF=0,AUTO=1,DEFAULT=1} uint8 modes[1]; Legacy nested[1]" + ) + assert wpistruct.pack(value) == b"A\x07\x01\x02\0\0\0\x03\0\x04\0" + assert wpistruct.unpack(AuthoredSingletonArrays, wpistruct.pack(value)) == value + + +@wpistruct.make_wpistruct +@dataclasses.dataclass +class AuthoredDescriptorArrays: + samples: tuple[wpistruct.uint16, wpistruct.uint16] + modes: Annotated[tuple[Mode, Mode], wpistruct.uint8] + nested: tuple[Legacy, Legacy] + + +def test_descriptor_codec_authored_arrays_larger_than_one_have_literal_layout(): + value = AuthoredDescriptorArrays( + (0x1234, 0xABCD), + (Mode.OFF, Mode.AUTO), + (Legacy(1, (2, 3)), Legacy(-1, (4, 5))), + ) + encoded = ( + b"\x34\x12\xcd\xab\x00\x01" + b"\x01\x00\x00\x00\x02\x00\x03\x00" + b"\xff\xff\xff\xff\x04\x00\x05\x00" + ) + + assert wpistruct.get_schema(AuthoredDescriptorArrays) == ( + "uint16 samples[2]; " + "enum {OFF=0,AUTO=1,DEFAULT=1} uint8 modes[2]; Legacy nested[2]" + ) + assert wpistruct.pack(value) == encoded + assert wpistruct.unpack(AuthoredDescriptorArrays, encoded) == value + + +@wpistruct.make_wpistruct +@dataclasses.dataclass +class SharedBits: + a: Annotated[wpistruct.int16, wpistruct.BitField(2)] + b: Annotated[bool, wpistruct.BitField(1)] + c: Annotated[bool, wpistruct.BitField(1)] + d: Annotated[wpistruct.uint16, wpistruct.BitField(5)] + + +def test_shared_bitfield_round_trip(): + value = SharedBits(-1, True, False, 17) + assert wpistruct.get_schema(SharedBits) == ( + "int16 a:2; bool b:1; bool c:1; uint16 d:5" + ) + assert wpistruct.get_size(SharedBits) == 2 + assert wpistruct.pack(value) == b"\x17\x01" + assert wpistruct.unpack(SharedBits, b"\x17\x01") == value + + +@wpistruct.make_wpistruct +@dataclasses.dataclass +class DifferentWidthBits: + a: Annotated[wpistruct.int32, wpistruct.BitField(2)] + b: Annotated[wpistruct.int16, wpistruct.BitField(2)] + + +@wpistruct.make_wpistruct +@dataclasses.dataclass +class OverflowBits: + a: Annotated[wpistruct.int8, wpistruct.BitField(4)] + b: Annotated[wpistruct.int8, wpistruct.BitField(5)] + + +@wpistruct.make_wpistruct +@dataclasses.dataclass +class BoolFirst8: + a: Annotated[bool, wpistruct.BitField(1)] + b: Annotated[wpistruct.int8, wpistruct.BitField(5)] + + +@wpistruct.make_wpistruct +@dataclasses.dataclass +class BoolFirst16: + a: Annotated[bool, wpistruct.BitField(1)] + b: Annotated[wpistruct.int16, wpistruct.BitField(5)] + + +@wpistruct.make_wpistruct +@dataclasses.dataclass +class BoolAfterFullUnit: + a: Annotated[wpistruct.int16, wpistruct.BitField(16)] + b: Annotated[bool, wpistruct.BitField(1)] + + +@pytest.mark.parametrize( + ("struct_type", "value", "size", "schema", "encoded"), + [ + ( + DifferentWidthBits, + DifferentWidthBits(-1, -2), + 6, + "int32 a:2; int16 b:2", + b"\x03\x00\x00\x00\x02\x00", + ), + ( + OverflowBits, + OverflowBits(-1, -2), + 2, + "int8 a:4; int8 b:5", + b"\x0f\x1e", + ), + ( + BoolFirst8, + BoolFirst8(True, -2), + 1, + "bool a:1; int8 b:5", + b"\x3d", + ), + ( + BoolFirst16, + BoolFirst16(True, -2), + 3, + "bool a:1; int16 b:5", + b"\x01\x1e\x00", + ), + ( + BoolAfterFullUnit, + BoolAfterFullUnit(-1, True), + 3, + "int16 a:16; bool b:1", + b"\xff\xff\x01", + ), + ], +) +def test_authored_bitfield_storage_transitions( + struct_type, value, size, schema, encoded +): + assert wpistruct.get_schema(struct_type) == schema + assert wpistruct.get_size(struct_type) == size + assert wpistruct.pack(value) == encoded + assert wpistruct.unpack(struct_type, encoded) == value + + +class SignedMode(enum.IntEnum): + REVERSE = -1 + FORWARD = 1 + + +@wpistruct.make_wpistruct +@dataclasses.dataclass +class MetadataOrder: + mode: Annotated[ + SignedMode, + wpistruct.BitField(2), + "application metadata", + wpistruct.int8, + ] + + +def test_complete_annotated_metadata_is_accepted_in_any_order(): + value = MetadataOrder(SignedMode.REVERSE) + assert wpistruct.get_schema(MetadataOrder) == ( + "enum {REVERSE=-1,FORWARD=1} int8 mode:2" + ) + assert wpistruct.pack(value) == b"\x03" + assert wpistruct.unpack(MetadataOrder, b"\x03") == value + + +class Huge(enum.IntEnum): + VALUE = 256 + + +class TooWideForSignedBitfield(enum.IntEnum): + VALUE = 2 + + +@pytest.mark.parametrize( + ("annotation", "match"), + [ + (Annotated[float, wpistruct.BitField(1)], "cannot be bitfield"), + (Annotated[wpistruct.char, wpistruct.BitField(1)], "cannot be bitfield"), + (Annotated[Legacy, wpistruct.BitField(1)], "cannot be bitfield"), + (Annotated[bool, wpistruct.BitField(2)], "width must be 1"), + ( + Annotated[wpistruct.int16, wpistruct.BitField(17)], + "exceeds type size", + ), + (Mode, "requires sized integer storage"), + ( + Annotated[Mode, wpistruct.uint8, wpistruct.int16], + "multiple storage", + ), + ( + Annotated[tuple[wpistruct.int8, wpistruct.int8], wpistruct.BitField(2)], + "array.*bitfield", + ), + (Annotated[Huge, wpistruct.uint8], "VALUE.*does not fit"), + ( + Annotated[ + TooWideForSignedBitfield, + wpistruct.int8, + wpistruct.BitField(2), + ], + "VALUE.*does not fit", + ), + ( + Annotated[str, wpistruct.CharArray(2), wpistruct.CharArray(3)], + "multiple CharArray", + ), + ( + Annotated[wpistruct.int8, wpistruct.CharArray(2)], + "CharArray.*only.*str", + ), + ( + Annotated[wpistruct.int8, wpistruct.BitField(1), wpistruct.BitField(1)], + "multiple bitfield", + ), + ], +) +def test_invalid_complete_grammar_annotations(annotation, match): + cls = dataclasses.make_dataclass("InvalidField", [("value", annotation)]) + with pytest.raises(TypeError, match=match): + wpistruct.make_wpistruct(cls) + + +@pytest.mark.parametrize( + ("text", "size", "encoded"), + [ + ("a\u0234", 3, b"a\xc8\xb4"), + ("a\u1234", 4, b"a\xe1\x88\xb4"), + ("a\U0001f400", 5, b"a\xf0\x9f\x90\x80"), + ], +) +def test_authored_char_array_utf8_boundaries_fit(text, size, encoded): + cls = dataclasses.make_dataclass( + f"Text{size}", [("text", Annotated[str, wpistruct.CharArray(size)])] + ) + wpistruct.make_wpistruct(cls) + + assert wpistruct.pack(cls(text)) == encoded + assert wpistruct.unpack(cls, encoded) == cls(text) + + +@pytest.mark.parametrize( + ("text", "size", "unchanged"), + [ + ("a\u0234", 2, b"\xa5\xa5"), + ("a\u1234", 2, b"\xa5\xa5"), + ("a\u1234", 3, b"\xa5\xa5\xa5"), + ("a\U0001f400", 2, b"\xa5\xa5"), + ("a\U0001f400", 3, b"\xa5\xa5\xa5"), + ("a\U0001f400", 4, b"\xa5\xa5\xa5\xa5"), + ], +) +def test_authored_char_array_rejects_partial_utf8_atomically(text, size, unchanged): + cls = dataclasses.make_dataclass( + f"Text{size}", [("text", Annotated[str, wpistruct.CharArray(size)])] + ) + wpistruct.make_wpistruct(cls) + destination = bytearray(unchanged) + + with pytest.raises(ValueError, match=rf"Text{size}: error packing data") as exc: + cls.WPIStruct.pack_into(cls(text), destination) + + assert str(exc.value.__cause__).endswith(f"must fit in {size} bytes") + assert destination == unchanged + + +@pytest.mark.parametrize( + ("number_type", "minimum", "maximum", "below", "above"), + [ + (wpistruct.int8, -(2**7), 2**7 - 1, -(2**7) - 1, 2**7), + (wpistruct.int16, -(2**15), 2**15 - 1, -(2**15) - 1, 2**15), + (wpistruct.int32, -(2**31), 2**31 - 1, -(2**31) - 1, 2**31), + (wpistruct.int64, -(2**63), 2**63 - 1, -(2**63) - 1, 2**63), + (wpistruct.uint8, 0, 2**8 - 1, -1, 2**8), + (wpistruct.uint16, 0, 2**16 - 1, -1, 2**16), + (wpistruct.uint32, 0, 2**32 - 1, -1, 2**32), + (wpistruct.uint64, 0, 2**64 - 1, -1, 2**64), + ], +) +def test_descriptor_codec_enforces_authored_integer_boundaries( + number_type, minimum, maximum, below, above +): + cls = dataclasses.make_dataclass( + f"Boundary{number_type.__name__}", + [("value", number_type), ("initial", wpistruct.char)], + ) + wpistruct.make_wpistruct(cls) + + for number in (minimum, maximum): + value = cls(number, wpistruct.char("A")) + assert wpistruct.unpack(cls, wpistruct.pack(value)) == value + + for number in (below, above): + with pytest.raises(ValueError, match="error packing data") as exc: + wpistruct.pack(cls(number, wpistruct.char("A"))) + assert "field value must be between" in str(exc.value.__cause__) + + +@wpistruct.make_wpistruct +@dataclasses.dataclass +class SignedNibble: + value: Annotated[wpistruct.int8, wpistruct.BitField(4)] + + +def test_authored_signed_bitfield_boundaries(): + for number in (-8, 7): + value = SignedNibble(number) + assert wpistruct.unpack(SignedNibble, wpistruct.pack(value)) == value + + for number in (-9, 8): + with pytest.raises(ValueError, match="error packing data") as exc: + wpistruct.pack(SignedNibble(number)) + assert "field value must be between -8 and 7" in str(exc.value.__cause__) + + +def test_descriptor_pack_into_callback_succeeds_atomically(): + value = Packet(wpistruct.char("A"), "ab\0c", Mode.AUTO) + destination = bytearray(b"\xa5" * wpistruct.get_size(Packet)) + + Packet.WPIStruct.pack_into(value, destination) + + assert destination == b"Aab\0c\0\x01" + + +def test_descriptor_codec_requires_enum_instances_and_pack_into_is_atomic(): + destination = bytearray(b"\xa5" * wpistruct.get_size(Packet)) + + with pytest.raises( + ValueError, + match=r"Packet \(test_struct_annotations\.Packet\): error packing data", + ) as exc: + Packet.WPIStruct.pack_into( + Packet(wpistruct.char("A"), "ok", 1), + destination, + ) + + assert "must be a Mode instance" in str(exc.value.__cause__) + assert destination == b"\xa5" * 7 + + +def test_descriptor_codec_preserves_unpack_error_wrapper(): + with pytest.raises( + ValueError, + match=r"Packet \(test_struct_annotations\.Packet\): error unpacking data", + ) as exc: + Packet.WPIStruct.unpack(b"\0") + + assert "buffer must be 7 bytes" in str(exc.value.__cause__) diff --git a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py new file mode 100644 index 000000000..c14672eb5 --- /dev/null +++ b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py @@ -0,0 +1,529 @@ +import dataclasses +import enum +import gc +import typing + +import pytest + +from wpiutil import wpistruct +import wpiutil.wpistruct._schema as schema_module +from wpiutil.wpistruct._schema import ( + InvalidStructSchema, + StructTypeRegistry, + make_wpistruct_from_schema, +) + + +def test_generate_struct_from_schema(): + generated = make_wpistruct_from_schema( + "Packet", + "int32 count; char name[4]; enum {OFF=0,AUTO=1} uint8 mode", + nested={}, + ) + assert dataclasses.is_dataclass(generated) + assert wpistruct.get_type_name(generated) == "Packet" + assert wpistruct.get_schema(generated) == ( + "int32 count; char name[4]; enum {OFF=0,AUTO=1} uint8 mode" + ) + mode_type = generated.__dataclass_fields__["mode"].type + value = wpistruct.unpack(generated, b"\x02\0\0\0abc\0\x01") + assert value.count == 2 + assert value.name == "abc" + assert isinstance(value.mode, mode_type) + assert value.mode.name == "AUTO" + assert wpistruct.pack(value) == b"\x02\0\0\0abc\0\x01" + + +def test_generated_struct_name_is_not_executed_as_source(): + generated = make_wpistruct_from_schema('Bad"Name', "uint8 value", nested={}) + assert wpistruct.get_type_name(generated) == 'Bad"Name' + assert wpistruct.unpack(generated, b"\x07") == generated(7) + + +def test_generated_struct_name_is_always_a_valid_identifier(): + generated = make_wpistruct_from_schema("¼", "uint8 value", nested={}) + assert generated.__name__ == "_" + assert generated.__name__.isidentifier() + assert wpistruct.get_type_name(generated) == "¼" + assert wpistruct.unpack(generated, b"\x07") == generated(7) + + +def test_generated_nested_struct_and_sanitized_field(): + inner = make_wpistruct_from_schema("Inner", "float32 value", nested={}) + outer = make_wpistruct_from_schema( + "pkg::Outer", "Inner class; float64 total", nested={"Inner": inner} + ) + value = wpistruct.unpack(outer, b"\0\0\xc0?\0\0\0\0\0\0\x04@") + assert value.class_.value == 1.5 + assert value.total == 2.5 + assert wpistruct.get_schema(outer) == "Inner class; float64 total" + schemas = [] + wpistruct.for_each_nested( + outer, lambda type_name, schema: schemas.append((type_name, schema)) + ) + assert schemas == [ + ("struct:Inner", "float32 value"), + ("struct:pkg::Outer", "Inner class; float64 total"), + ] + assert outer.__wpistruct_descriptor__.type_name == "pkg::Outer" + assert outer.__wpistruct_descriptor__.fields[0].schema_name == "class" + assert outer.__wpistruct_descriptor__.fields[0].python_name == "class_" + + +def test_generated_fixed_arrays(): + inner = make_wpistruct_from_schema("Inner", "uint8 value", nested={}) + outer = make_wpistruct_from_schema( + "Outer", "uint16 samples[2]; Inner children[2]", nested={"Inner": inner} + ) + value = outer((1, 2), (inner(3), inner(4))) + assert wpistruct.unpack(outer, wpistruct.pack(value)) == value + + +def test_generated_explicit_singleton_arrays_preserve_tuple_values_and_bytes(): + inner = make_wpistruct_from_schema("SingletonInner", "uint16 value", nested={}) + generated = make_wpistruct_from_schema( + "GeneratedSingletonArrays", + "uint8 samples[1]; enum {OFF=0,AUTO=1} uint8 modes[1]; " + "SingletonInner children[1]", + nested={"SingletonInner": inner}, + ) + mode_type = typing.get_args(generated.__dataclass_fields__["modes"].type)[0] + value = generated((7,), (mode_type.AUTO,), (inner(0x1234),)) + encoded = b"\x07\x01\x34\x12" + + assert wpistruct.get_schema(generated) == ( + "uint8 samples[1]; enum {OFF=0,AUTO=1} uint8 modes[1]; " + "SingletonInner children[1]" + ) + assert wpistruct.pack(value) == encoded + assert wpistruct.unpack(generated, encoded) == value + assert isinstance(value.samples, tuple) + assert isinstance(value.modes, tuple) + assert isinstance(value.children, tuple) + + +def test_many_scalar_fields_do_not_trigger_per_field_schema_scans(monkeypatch): + scan_calls = 0 + original_compile = schema_module.re.compile + original_search = schema_module.re.search + + def counting_compile(pattern, *args, **kwargs): + nonlocal scan_calls + if isinstance(pattern, str) and "(?P" in pattern: + scan_calls += 1 + return original_compile(pattern, *args, **kwargs) + + def counting_search(pattern, *args, **kwargs): + nonlocal scan_calls + if isinstance(pattern, str) and "(?:enum\\s*)?" in pattern: + scan_calls += 1 + return original_search(pattern, *args, **kwargs) + + monkeypatch.setattr(schema_module.re, "compile", counting_compile) + monkeypatch.setattr(schema_module.re, "search", counting_search) + field_count = 256 + schema = "; ".join(f"uint8 value{i}" for i in range(field_count)) + + generated = make_wpistruct_from_schema("ManyScalars", schema, nested={}) + + assert len(dataclasses.fields(generated)) == field_count + assert scan_calls <= 1 + + +def test_generated_array_representability_limit(): + largest = make_wpistruct_from_schema( + "LargestGeneratedArray", "uint8 values[65536]", nested={} + ) + assert wpistruct.get_size(largest) == 65536 + + with pytest.raises( + ValueError, + match=( + r"generated wpistruct arrays contain 65537 total elements; " + r"support at most 65536" + ), + ): + make_wpistruct_from_schema( + "OversizedGeneratedArray", "uint8 values[65537]", nested={} + ) + + +def test_generated_array_representability_budget_is_cumulative(): + with pytest.raises( + ValueError, + match=( + r"generated wpistruct arrays contain 65538 total elements; " + r"support at most 65536" + ), + ): + make_wpistruct_from_schema( + "CumulativelyOversizedGeneratedArrays", + "uint8 first[32769]; uint8 second[32769]", + nested={}, + ) + + +def test_generated_empty_schema_and_float_aliases(): + empty = make_wpistruct_from_schema("Empty", "", nested={}) + aliases = make_wpistruct_from_schema( + "Aliases", "float32 first; float64 second", nested={} + ) + assert wpistruct.get_size(empty) == 0 + assert wpistruct.unpack(empty, b"") == empty() + assert wpistruct.get_schema(aliases) == "float32 first; float64 second" + assert wpistruct.unpack(aliases, wpistruct.pack(aliases(1.5, 2.5))) == aliases( + 1.5, 2.5 + ) + + +def test_generated_identifier_collision_is_deterministic(): + generated = make_wpistruct_from_schema( + "pkg::Collision", "uint8 class; uint8 class_", nested={} + ) + assert [field.name for field in dataclasses.fields(generated)] == [ + "class_", + "class_2", + ] + assert [ + field.python_name for field in generated.__wpistruct_descriptor__.fields + ] == [ + "class_", + "class_2", + ] + + +def test_generated_special_attribute_names_are_sanitized(): + generated = make_wpistruct_from_schema( + "SpecialFields", + "uint8 __class__; uint8 __dict__; uint8 __weakref__; " + "uint8 __dataclass_fields__; uint8 __dataclass_params__; uint8 __match_args__; " + "uint8 mro; uint8 __module__; uint8 __doc__; uint8 __repr__", + nested={}, + ) + assert [field.name for field in dataclasses.fields(generated)] == [ + "__class___", + "__dict___", + "__weakref___", + "__dataclass_fields___", + "__dataclass_params___", + "__match_args___", + "mro_", + "__module___", + "__doc___", + "__repr___", + ] + value = generated(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + assert wpistruct.unpack(generated, wpistruct.pack(value)) == value + + +def test_generated_metadata_reservation_does_not_change_other_identifiers(): + generated = make_wpistruct_from_schema( + "WPIStruct", "enum {WPIStruct=1} uint8 mode", nested={} + ) + assert generated.__name__ == "WPIStruct" + mode_type = generated.__dataclass_fields__["mode"].type + assert list(mode_type.__members__) == ["WPIStruct"] + assert wpistruct.get_type_name(generated) == "WPIStruct" + + +def test_generated_serializer_metadata_names_are_sanitized(): + generated = make_wpistruct_from_schema( + "MetadataFields", + "uint8 WPIStruct; uint8 WPIStruct_; " + "uint8 __wpistruct_descriptor__; uint8 __wpistruct_descriptor___", + nested={}, + ) + assert [field.name for field in dataclasses.fields(generated)] == [ + "WPIStruct_", + "WPIStruct_2", + "__wpistruct_descriptor___", + "__wpistruct_descriptor___2", + ] + assert [ + field.schema_name for field in generated.__wpistruct_descriptor__.fields + ] == [ + "WPIStruct", + "WPIStruct_", + "__wpistruct_descriptor__", + "__wpistruct_descriptor___", + ] + value = generated(1, 2, 3, 4) + assert wpistruct.unpack(generated, wpistruct.pack(value)) == value + + +def test_generated_enum_class_names_follow_field_collisions(): + generated = make_wpistruct_from_schema( + "CollisionEnums", + "enum {A=1} uint8 class; enum {B=2} uint8 class_; " + "enum {C=3} uint8 mode; enum {D=4} uint8 Mode", + nested={}, + ) + first = generated.__dataclass_fields__["class_"].type + second = generated.__dataclass_fields__["class_2"].type + assert first is not second + assert first.__name__ == "CollisionEnumsClass_" + third = generated.__dataclass_fields__["mode"].type + fourth = generated.__dataclass_fields__["Mode"].type + assert second.__name__ == "CollisionEnumsClass_2" + assert third.__name__ == "CollisionEnumsMode" + assert fourth.__name__ == "CollisionEnumsMode_2" + + +def test_generated_reserved_enum_names_and_aliases_are_preserved(): + generated = make_wpistruct_from_schema( + "ReservedEnum", + "enum {_missing_=1,_missing_member=1,__class__=2,mro=3} uint8 mode", + nested={}, + ) + mode_type = generated.__dataclass_fields__["mode"].type + assert list(mode_type.__members__) == [ + "_missing_member", + "_missing_member_2", + "__class___member", + "mro_", + ] + assert mode_type._missing_member_2 is mode_type._missing_member + assert generated.__wpistruct_descriptor__.fields[0].enum_values == ( + ("_missing_", 1), + ("_missing_member", 1), + ("__class__", 2), + ("mro", 3), + ) + + +@pytest.mark.parametrize("schema", ["{}uint8 mode", "enum{}uint8 mode"]) +def test_generated_empty_enum_is_typed(schema): + generated = make_wpistruct_from_schema("EmptyMode", schema, nested={}) + mode_type = generated.__dataclass_fields__["mode"].type + assert issubclass(mode_type, enum.IntEnum) + value = wpistruct.unpack(generated, b"\x07") + assert isinstance(value.mode, mode_type) + assert value.mode.name == "UNKNOWN_7" + + +def test_generated_unknown_enum_is_typed(): + generated = make_wpistruct_from_schema( + "ModeValue", "enum {OFF=0,AUTO=1} uint8 mode", nested={} + ) + value = wpistruct.unpack(generated, b"\x07") + assert isinstance(value.mode, generated.__dataclass_fields__["mode"].type) + assert value.mode.name == "UNKNOWN_7" + assert value.mode.value == 7 + + +def test_generated_type_outlives_registry(): + registry = StructTypeRegistry(()) + generated = registry.add_schema("Value", "uint8 value") + del registry + gc.collect() + assert wpistruct.unpack(generated, b"\x07") == generated(7) + assert wpistruct.pack(generated(8)) == b"\x08" + + +def test_registry_requires_nested_type_first(): + registry = StructTypeRegistry(()) + with pytest.raises(ValueError, match="Inner.*not registered"): + registry.add_schema("Outer", "Inner value") + + +def test_registry_independent_schemas_use_one_native_add_each(monkeypatch): + native_database = schema_module.SchemaDatabase + + class CountingSchemaDatabase: + instances = [] + add_calls = [] + stage_calls = [] + + def __init__(self, wrapped=None): + self._wrapped = wrapped or native_database() + self.instance_adds = [] + type(self).instances.append(self) + + def add(self, type_name, schema): + self.instance_adds.append(type_name) + type(self).add_calls.append(type_name) + return self._wrapped.add(type_name, schema) + + def find(self, type_name): + return self._wrapped.find(type_name) + + def stage(self, type_name, schema): + type(self).stage_calls.append(type_name) + return type(self)(self._wrapped.stage(type_name, schema)) + + monkeypatch.setattr(schema_module, "SchemaDatabase", CountingSchemaDatabase) + registry = StructTypeRegistry(()) + schema_count = 64 + expected_names = [f"Value{index}" for index in range(schema_count)] + + for type_name in expected_names: + registry.add_schema(type_name, "uint8 value") + + assert CountingSchemaDatabase.stage_calls == [] + assert CountingSchemaDatabase.add_calls == expected_names + assert [ + database.instance_adds + for database in CountingSchemaDatabase.instances + if database.instance_adds + ] == [[type_name] for type_name in expected_names] + + +def test_failed_generated_class_construction_does_not_mutate_registry(): + registry = StructTypeRegistry(()) + + with pytest.raises(ValueError, match="support at most 65536"): + registry.add_schema("Value", "uint8 samples[65537]") + + recovered = registry.add_schema("Value", "uint8 value") + assert wpistruct.unpack(recovered, b"\x07") == recovered(7) + + +def test_failed_unresolved_registry_schema_does_not_reserve_name(): + registry = StructTypeRegistry(()) + + with pytest.raises(ValueError, match="Inner.*not registered"): + registry.add_schema("Outer", "Inner value") + + recovered = registry.add_schema("Outer", "uint8 value") + assert wpistruct.get_schema(recovered) == "uint8 value" + assert wpistruct.unpack(recovered, b"\x07") == recovered(7) + + +def test_failed_unresolved_registry_schema_can_retry_after_nested_registration(): + registry = StructTypeRegistry(()) + + with pytest.raises(ValueError, match="Inner.*not registered"): + registry.add_schema("Outer", "Inner value") + + inner = registry.add_schema("Inner", "uint8 value") + outer = registry.add_schema("Outer", "Inner value") + value = outer(inner(7)) + assert wpistruct.unpack(outer, wpistruct.pack(value)) == value + + +def test_registry_duplicate_and_conflict_behavior(): + registry = StructTypeRegistry(()) + first = registry.add_schema("Value", "int32 value;") + assert registry.add_schema("Value", " int32 value ") is first + with pytest.raises(ValueError, match="conflicting schema for Value"): + registry.add_schema("Value", "uint32 value") + + +def test_registry_malformed_schema_is_distinct_error(): + with pytest.raises(InvalidStructSchema, match="expected identifier"): + StructTypeRegistry(()).add_schema("Bad", "int32 [2]") + + +def test_direct_generation_preserves_schema_error_taxonomy(): + with pytest.raises(InvalidStructSchema, match="expected identifier"): + make_wpistruct_from_schema("Bad", "int32 [2]", nested={}) + + for schema, match, exception_type in ( + ( + "Missing value", + "Missing.*not registered", + schema_module._UnresolvedStructSchema, + ), + ("uint8 value; uint8 value", "duplicate field value", ValueError), + ): + with pytest.raises(ValueError, match=match) as exc_info: + make_wpistruct_from_schema("Semantic", schema, nested={}) + assert type(exc_info.value) is exception_type + + +def test_non_ascii_parser_failures_preserve_schema_error_taxonomy(): + with pytest.raises(InvalidStructSchema): + make_wpistruct_from_schema("Bad", "uint8 é", nested={}) + with pytest.raises(InvalidStructSchema): + StructTypeRegistry(()).add_schema("Bad", "uint8 é") + + +def test_registry_accepts_supplied_nested_unicode_authored_structs(): + inner = dataclasses.make_dataclass( + "SuppliedUnicodeInner", [("变量", wpistruct.uint16)] + ) + inner = wpistruct.make_wpistruct(name="SuppliedUnicodeInner")(inner) + outer = dataclasses.make_dataclass( + "SuppliedUnicodeOuter", [("π", inner), ("aé", wpistruct.int8)] + ) + outer = wpistruct.make_wpistruct(name="SuppliedUnicodeOuter")(outer) + + registry = StructTypeRegistry((outer,)) + + assert registry.get("SuppliedUnicodeOuter") is outer + value = outer(inner(0x1234), -2) + assert wpistruct.unpack(outer, wpistruct.pack(value)) == value + + +@wpistruct.make_wpistruct(name="Supplied") +@dataclasses.dataclass +class Supplied: + value: wpistruct.int32 + + +@wpistruct.make_wpistruct(name="Supplied") +@dataclasses.dataclass +class OtherSupplied: + value: wpistruct.uint32 + + +def test_registry_supplied_type_lookup_and_precedence(): + registry = StructTypeRegistry((Supplied,)) + assert registry.get("Supplied") is Supplied + assert registry.add_schema("Supplied", "uint32 incompatible") is Supplied + + +def test_registry_rejects_duplicate_supplied_name_eagerly(): + with pytest.raises(ValueError, match="duplicate supplied struct type Supplied"): + StructTypeRegistry((Supplied, OtherSupplied)) + + +@wpistruct.make_wpistruct(name="Child") +@dataclasses.dataclass +class Child: + value: wpistruct.uint8 + + +@wpistruct.make_wpistruct(name="Parent") +@dataclasses.dataclass +class Parent: + child: Child + + +@wpistruct.make_wpistruct(name="SeededShapeChild") +@dataclasses.dataclass +class SeededShapeChild: + value: wpistruct.uint8 + + +@wpistruct.make_wpistruct(name="SeededShapeParent") +@dataclasses.dataclass +class SeededShapeParent: + child: SeededShapeChild + + +def test_registry_logged_equivalent_nested_schema_uses_logged_shape(): + registry = StructTypeRegistry((SeededShapeParent,)) + + generated = registry.add_schema("SeededShapeChild", "uint8 value[1]") + value = wpistruct.unpack(generated, b"\x07") + + layout = generated.__wpistruct_descriptor__ + generated_field = generated.__dataclass_fields__["value"] + + assert value.value == (7,) + assert typing.get_origin(generated_field.type) is tuple + assert wpistruct.get_schema(generated) == "uint8 value[1]" + assert layout.schema == "uint8 value[1]" + assert layout.schema == wpistruct.get_schema(generated) + assert layout.fields[0].array_size == 1 + assert SeededShapeChild.__wpistruct_descriptor__.schema == "uint8 value" + assert wpistruct.pack(value) == b"\x07" + + +def test_registry_seeds_supplied_nested_schemas_child_first(): + registry = StructTypeRegistry((Child, Parent)) + wrapper = registry.add_schema("Wrapper", "Parent parent") + assert wpistruct.unpack( + wrapper, wpistruct.pack(wrapper(Parent(Child(3)))) + ) == wrapper(Parent(Child(3))) diff --git a/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_fns.cpp b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_fns.cpp index 3d5739437..408bb4ddb 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_fns.cpp +++ b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_fns.cpp @@ -85,11 +85,13 @@ void packInto(const WPyStruct& v, py::buffer& b) { WPyStructInfo info(v); py::ssize_t sz = wpi::util::GetStructSize(info); - auto req = b.request(); + auto req = b.request(true); if (req.itemsize != 1) { throw py::value_error("buffer must only contain bytes"); } else if (req.ndim != 1) { throw py::value_error("buffer must only have a single dimension"); + } else if (req.strides[0] != 1) { + throw py::value_error("buffer must be contiguous"); } if (req.size != sz) { @@ -131,6 +133,10 @@ py::typing::List unpackArray(const py::type& t, throw py::value_error("buffer must only have a single dimension"); } + if (sz == 0) { + throw py::value_error("cannot unpack an array of zero-size structs"); + } + if (req.size % sz != 0) { throw py::value_error("buffer must be multiple of " + std::to_string(sz) + " bytes"); diff --git a/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.cpp b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.cpp new file mode 100644 index 000000000..03ab496fb --- /dev/null +++ b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.cpp @@ -0,0 +1,727 @@ +#include "wpystruct_schema.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "wpi/util/struct/DynamicStruct.hpp" +#include "wpi/util/struct/SchemaParser.hpp" + +namespace wpy::structs { + +struct DeclarationShape { + bool isArray = false; + bool isBitField = false; + bool isEnum = false; +}; + +class SchemaDatabaseImpl { + public: + std::shared_ptr database = + std::make_shared(); + std::map> definitions; + std::map, std::less<>> shapes; +}; + +namespace { + +const wpi::util::StructDescriptor& ResolveDescriptor( + const std::shared_ptr& database, + std::string_view name) { + const auto* descriptor = database->Find(name); + if (!descriptor) { + throw pybind11::value_error("descriptor " + std::string{name} + + " does not exist"); + } + return *descriptor; +} + +const wpi::util::StructDescriptor& ResolveDescriptor( + const std::shared_ptr& impl, std::string_view name) { + return ResolveDescriptor(impl->database, name); +} + +std::string_view NormalizeType(std::string_view type) { + if (type == "float32") { + return "float"; + } + if (type == "float64") { + return "double"; + } + return type; +} + +unsigned int NormalizeBitWidth( + const wpi::util::structparser::ParsedDeclaration& declaration) { + if (declaration.bitWidth != 0) { + return declaration.bitWidth; + } + + auto type = NormalizeType(declaration.typeString); + if (type == "int8" || type == "uint8") { + return 8; + } + if (type == "int16" || type == "uint16") { + return 16; + } + if (type == "int32" || type == "uint32") { + return 32; + } + if (type == "int64" || type == "uint64") { + return 64; + } + return 0; +} + +bool DeclarationsEqual(const wpi::util::structparser::ParsedDeclaration& lhs, + const wpi::util::structparser::ParsedDeclaration& rhs) { + return NormalizeType(lhs.typeString) == NormalizeType(rhs.typeString) && + lhs.name == rhs.name && lhs.enumValues == rhs.enumValues && + lhs.arraySize == rhs.arraySize && + NormalizeBitWidth(lhs) == NormalizeBitWidth(rhs); +} + +wpi::util::structparser::ParsedSchema ParseSchema(std::string_view schema) { + wpi::util::structparser::Parser parser{schema}; + wpi::util::structparser::ParsedSchema parsed; + if (!parser.Parse(&parsed)) { + throw pybind11::value_error("parse error: " + parser.GetError()); + } + return parsed; +} + +std::vector ParseDeclarationShapes(std::string_view schema) { + wpi::util::structparser::Lexer lexer{schema}; + std::vector shapes; + DeclarationShape shape; + bool hasDeclaration = false; + while (true) { + auto token = lexer.Scan(); + if (token.Is(wpi::util::structparser::Token::END_OF_INPUT)) { + if (hasDeclaration) { + shapes.emplace_back(shape); + } + return shapes; + } + if (token.Is(wpi::util::structparser::Token::SEMICOLON)) { + if (hasDeclaration) { + shapes.emplace_back(shape); + shape = {}; + hasDeclaration = false; + } + continue; + } + + hasDeclaration = true; + if (token.Is(wpi::util::structparser::Token::LEFT_BRACE)) { + shape.isEnum = true; + } else if (token.Is(wpi::util::structparser::Token::LEFT_BRACKET)) { + shape.isArray = true; + } else if (token.Is(wpi::util::structparser::Token::COLON)) { + shape.isBitField = true; + } + } +} + +bool SchemasEqual(std::string_view lhs, std::string_view rhs) { + auto parsedLhs = ParseSchema(lhs); + auto parsedRhs = ParseSchema(rhs); + if (parsedLhs.declarations.size() != parsedRhs.declarations.size()) { + return false; + } + for (size_t i = 0; i < parsedLhs.declarations.size(); ++i) { + if (!DeclarationsEqual(parsedLhs.declarations[i], + parsedRhs.declarations[i])) { + return false; + } + } + return true; +} + +void ValidateArrayExtentsForPlatform(std::string_view descriptorName, + std::string_view schema) { + wpi::util::structparser::Lexer lexer{schema}; + wpi::util::structparser::Token previous; + for (auto token = lexer.Scan(); + !token.Is(wpi::util::structparser::Token::END_OF_INPUT); + token = lexer.Scan()) { + if (token.Is(wpi::util::structparser::Token::LEFT_BRACKET)) { + auto extentToken = lexer.Scan(); + uint64_t extent = 0; + auto result = std::from_chars( + extentToken.text.data(), + extentToken.text.data() + extentToken.text.size(), extent); + if (extentToken.Is(wpi::util::structparser::Token::INTEGER) && + result.ec == std::errc{} && + extent > std::numeric_limits::max()) { + std::string fieldName = + previous.Is(wpi::util::structparser::Token::IDENTIFIER) + ? std::string{previous.text} + : ""; + throw pybind11::value_error( + "unsafe schema layout for " + std::string{descriptorName} + + ": field " + fieldName + " storage extent exceeds platform limits"); + } + previous = extentToken; + } else { + previous = token; + } + } +} + +void ValidateDescriptorLayout(const wpi::util::StructDescriptor& descriptor) { + if (!descriptor.IsValid()) { + return; + } + + const size_t descriptorSize = descriptor.GetSize(); + for (const auto& field : descriptor.GetFields()) { + const size_t fieldSize = field.GetSize(); + const size_t arraySize = field.GetArraySize(); + if (fieldSize != 0 && + arraySize > std::numeric_limits::max() / fieldSize) { + throw pybind11::value_error( + "unsafe schema layout for " + descriptor.GetName() + ": field " + + field.GetName() + " storage extent exceeds platform limits"); + } + + const size_t storageExtent = fieldSize * arraySize; + const size_t offset = field.GetOffset(); + if (offset > descriptorSize || storageExtent > descriptorSize - offset) { + throw pybind11::value_error( + "unsafe schema layout for " + descriptor.GetName() + ": field " + + field.GetName() + " storage extent exceeds descriptor size"); + } + } +} + +void ValidateDatabaseLayouts( + const wpi::util::StructDescriptorDatabase& database, + const std::map>& definitions, + std::string_view candidateName) { + for (const auto& definition : definitions) { + const auto* descriptor = database.Find(definition.first); + if (!descriptor) { + throw pybind11::value_error("failed to reconstruct schema database"); + } + ValidateDescriptorLayout(*descriptor); + } + + const auto* candidate = database.Find(candidateName); + if (!candidate) { + throw pybind11::value_error("failed to reconstruct schema database"); + } + ValidateDescriptorLayout(*candidate); +} + +std::shared_ptr BuildStagedDatabase( + const std::shared_ptr& source, std::string_view name, + std::string_view schema) { + auto parsed = ParseSchema(schema); + auto shapes = ParseDeclarationShapes(schema); + if (shapes.size() != parsed.declarations.size()) { + throw pybind11::value_error("failed to analyze schema declarations"); + } + ValidateArrayExtentsForPlatform(name, schema); + + bool duplicate = false; + if (auto existing = source->definitions.find(name); + existing != source->definitions.end()) { + if (!SchemasEqual(existing->second, schema)) { + throw pybind11::value_error("conflicting schema for " + + std::string{name}); + } + duplicate = true; + } + + auto staged = std::make_shared(); + staged->definitions = source->definitions; + staged->shapes = source->shapes; + std::string error; + for (const auto& [definedName, definedSchema] : source->definitions) { + if (!staged->database->Add(definedName, definedSchema, &error)) { + throw pybind11::value_error("failed to reconstruct schema database: " + + error); + } + } + if (duplicate) { + staged->definitions[std::string{name}] = std::string{schema}; + staged->shapes[std::string{name}] = std::move(shapes); + return staged; + } + + const auto* descriptor = staged->database->Add(name, schema, &error); + if (!descriptor) { + throw pybind11::value_error(error); + } + std::string descriptorName = descriptor->GetName(); + ValidateDatabaseLayouts(*staged->database, source->definitions, + descriptorName); + staged->definitions.emplace(descriptorName, schema); + staged->shapes.emplace(std::move(descriptorName), std::move(shapes)); + return staged; +} + +std::string FieldTypeName(const wpi::util::StructFieldDescriptor& field) { + using wpi::util::StructFieldType; + + switch (field.GetType()) { + case StructFieldType::BOOL: + return "bool"; + case StructFieldType::CHAR: + return "char"; + case StructFieldType::INT8: + return "int8"; + case StructFieldType::INT16: + return "int16"; + case StructFieldType::INT32: + return "int32"; + case StructFieldType::INT64: + return "int64"; + case StructFieldType::UINT8: + return "uint8"; + case StructFieldType::UINT16: + return "uint16"; + case StructFieldType::UINT32: + return "uint32"; + case StructFieldType::UINT64: + return "uint64"; + case StructFieldType::FLOAT: + return "float"; + case StructFieldType::DOUBLE: + return "double"; + case StructFieldType::STRUCT: + return field.GetStruct()->GetName(); + } + return {}; +} + +std::string FieldError(const wpi::util::StructFieldDescriptor& field, + std::string_view message) { + return "field " + field.GetName() + " " + std::string{message}; +} + +void RequireBool(const wpi::util::StructFieldDescriptor& field, + py::handle value) { + if (!PyBool_Check(value.ptr())) { + throw py::type_error(FieldError(field, "must be a bool")); + } +} + +void RequireFloat(const wpi::util::StructFieldDescriptor& field, + py::handle value) { + if (!PyFloat_Check(value.ptr())) { + throw py::type_error(FieldError(field, "must be a float")); + } +} + +void RequireIntegerType(const wpi::util::StructFieldDescriptor& field, + py::handle value) { + if (!PyLong_Check(value.ptr()) || PyBool_Check(value.ptr())) { + throw py::type_error(FieldError(field, "must be an integer")); + } +} + +template +[[noreturn]] +void ThrowIntegerRangeError(const wpi::util::StructFieldDescriptor& field, + T minimum, T maximum) { + throw py::value_error( + FieldError(field, "must be between " + std::to_string(minimum) + " and " + + std::to_string(maximum))); +} + +int64_t RequireSignedInteger(const wpi::util::StructFieldDescriptor& field, + py::handle value, int64_t minimum, + int64_t maximum) { + RequireIntegerType(field, value); + int overflow = 0; + int64_t converted = PyLong_AsLongLongAndOverflow(value.ptr(), &overflow); + if (converted == -1 && PyErr_Occurred()) { + throw py::error_already_set(); + } + if (overflow != 0 || converted < minimum || converted > maximum) { + ThrowIntegerRangeError(field, minimum, maximum); + } + return converted; +} + +uint64_t RequireUnsignedInteger(const wpi::util::StructFieldDescriptor& field, + py::handle value, uint64_t minimum, + uint64_t maximum) { + RequireIntegerType(field, value); + uint64_t converted = PyLong_AsUnsignedLongLong(value.ptr()); + if (PyErr_Occurred()) { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) { + throw py::error_already_set(); + } + PyErr_Clear(); + ThrowIntegerRangeError(field, minimum, maximum); + } + if (converted < minimum || converted > maximum) { + ThrowIntegerRangeError(field, minimum, maximum); + } + return converted; +} + +float RequireFloat32(const wpi::util::StructFieldDescriptor& field, + py::handle value) { + RequireFloat(field, value); + double converted = PyFloat_AsDouble(value.ptr()); + if (converted == -1.0 && PyErr_Occurred()) { + throw py::error_already_set(); + } + constexpr double kMax = std::numeric_limits::max(); + if (std::isfinite(converted) && (converted < -kMax || converted > kMax)) { + throw py::value_error(FieldError(field, "must be within float32 range")); + } + return static_cast(converted); +} + +py::sequence RequireArray(const wpi::util::StructFieldDescriptor& field, + py::handle value) { + if (!PySequence_Check(value.ptr()) || PyUnicode_Check(value.ptr())) { + throw py::type_error(FieldError(field, "must be a sequence")); + } + auto sequence = py::reinterpret_borrow(value); + if (sequence.size() != field.GetArraySize()) { + throw py::value_error(FieldError( + field, + "must contain " + std::to_string(field.GetArraySize()) + " values")); + } + return sequence; +} + +std::span RequireNestedBytes( + const wpi::util::StructFieldDescriptor& field, py::handle value) { + if (!PyBytes_Check(value.ptr())) { + throw py::type_error(FieldError(field, "must be bytes")); + } + char* data; + Py_ssize_t size; + if (PyBytes_AsStringAndSize(value.ptr(), &data, &size) != 0) { + throw py::error_already_set(); + } + size_t expected = field.GetStruct()->GetSize(); + if (size != static_cast(expected)) { + throw py::value_error( + FieldError(field, "must be " + std::to_string(expected) + " bytes")); + } + return {reinterpret_cast(data), expected}; +} + +void PackElement(wpi::util::MutableDynamicStruct& output, + const wpi::util::StructFieldDescriptor& field, + py::handle value, size_t index) { + using wpi::util::StructFieldType; + + switch (field.GetType()) { + case StructFieldType::BOOL: + RequireBool(field, value); + output.SetBoolField(&field, value.ptr() == Py_True, index); + return; + case StructFieldType::INT8: + case StructFieldType::INT16: + case StructFieldType::INT32: + case StructFieldType::INT64: + output.SetIntField(&field, + RequireSignedInteger(field, value, field.GetIntMin(), + field.GetIntMax()), + index); + return; + case StructFieldType::UINT8: + case StructFieldType::UINT16: + case StructFieldType::UINT32: + case StructFieldType::UINT64: + output.SetUintField( + &field, + RequireUnsignedInteger(field, value, field.GetUintMin(), + field.GetUintMax()), + index); + return; + case StructFieldType::FLOAT: + output.SetFloatField(&field, RequireFloat32(field, value), index); + return; + case StructFieldType::DOUBLE: + RequireFloat(field, value); + output.SetDoubleField(&field, py::cast(value), index); + return; + case StructFieldType::STRUCT: { + auto data = RequireNestedBytes(field, value); + wpi::util::DynamicStruct nested{field.GetStruct(), data}; + output.SetStructField(&field, nested, index); + return; + } + case StructFieldType::CHAR: + throw py::type_error(FieldError(field, "must be a string")); + } +} + +void PackField(wpi::util::MutableDynamicStruct& output, + const wpi::util::StructFieldDescriptor& field, + py::handle value) { + if (field.GetType() == wpi::util::StructFieldType::CHAR) { + if (!PyUnicode_Check(value.ptr())) { + throw py::type_error(FieldError(field, "must be a string")); + } + Py_ssize_t size; + const char* data = PyUnicode_AsUTF8AndSize(value.ptr(), &size); + if (!data) { + throw py::error_already_set(); + } + if (!output.SetStringField(&field, {data, static_cast(size)})) { + throw py::value_error(FieldError( + field, + "must fit in " + std::to_string(field.GetArraySize()) + " bytes")); + } + return; + } + + if (field.IsArray()) { + auto sequence = RequireArray(field, value); + for (size_t i = 0; i < field.GetArraySize(); ++i) { + PackElement(output, field, sequence[static_cast(i)], i); + } + return; + } + + PackElement(output, field, value, 0); +} + +int64_t UnpackSignedElement(const wpi::util::DynamicStruct& input, + const wpi::util::StructFieldDescriptor& field, + size_t index) { + uint64_t raw = static_cast(input.GetIntField(&field, index)); + unsigned int width = field.GetBitWidth(); + if (width < 64 && (raw & (uint64_t{1} << (width - 1))) != 0) { + raw |= ~field.GetBitMask(); + } + return static_cast(raw); +} + +py::object UnpackElement(const wpi::util::DynamicStruct& input, + const wpi::util::StructFieldDescriptor& field, + size_t index) { + using wpi::util::StructFieldType; + + switch (field.GetType()) { + case StructFieldType::BOOL: + return py::bool_{input.GetBoolField(&field, index)}; + case StructFieldType::INT8: + case StructFieldType::INT16: + case StructFieldType::INT32: + case StructFieldType::INT64: + return py::int_{UnpackSignedElement(input, field, index)}; + case StructFieldType::UINT8: + case StructFieldType::UINT16: + case StructFieldType::UINT32: + case StructFieldType::UINT64: + return py::int_{input.GetUintField(&field, index)}; + case StructFieldType::FLOAT: + return py::float_{input.GetFloatField(&field, index)}; + case StructFieldType::DOUBLE: + return py::float_{input.GetDoubleField(&field, index)}; + case StructFieldType::STRUCT: { + auto data = input.GetStructField(&field, index).GetData(); + return py::bytes{reinterpret_cast(data.data()), + field.GetStruct()->GetSize()}; + } + case StructFieldType::CHAR: + break; + } + throw py::type_error(FieldError(field, "has an unsupported type")); +} + +py::object UnpackField(const wpi::util::DynamicStruct& input, + const wpi::util::StructFieldDescriptor& field) { + if (field.GetType() == wpi::util::StructFieldType::CHAR) { + auto value = input.GetStringField(&field); + PyObject* decoded = + PyUnicode_DecodeUTF8(value.data(), value.size(), "strict"); + if (!decoded) { + throw py::error_already_set(); + } + return py::reinterpret_steal(decoded); + } + + if (field.IsArray()) { + py::tuple values{static_cast(field.GetArraySize())}; + for (size_t i = 0; i < field.GetArraySize(); ++i) { + values[static_cast(i)] = UnpackElement(input, field, i); + } + return values; + } + + return UnpackElement(input, field, 0); +} + +} // namespace + +SchemaDescriptor::SchemaDescriptor(std::shared_ptr impl, + std::string name) + : m_impl{std::move(impl)}, m_name{std::move(name)} {} + +std::string SchemaDescriptor::GetName() const { + return ResolveDescriptor(m_impl, m_name).GetName(); +} + +std::string SchemaDescriptor::GetSchema() const { + if (auto definition = m_impl->definitions.find(m_name); + definition != m_impl->definitions.end()) { + return definition->second; + } + return ResolveDescriptor(m_impl, m_name).GetSchema(); +} + +bool SchemaDescriptor::IsValid() const { + return ResolveDescriptor(m_impl, m_name).IsValid(); +} + +size_t SchemaDescriptor::GetSize() const { + const auto& descriptor = ResolveDescriptor(m_impl, m_name); + if (!descriptor.IsValid()) { + throw pybind11::value_error("descriptor " + m_name + " is not valid"); + } + return descriptor.GetSize(); +} + +std::vector SchemaDescriptor::GetFields() const { + const auto& descriptor = ResolveDescriptor(m_impl, m_name); + const auto& nativeFields = descriptor.GetFields(); + const auto shapeIt = m_impl->shapes.find(m_name); + if (shapeIt == m_impl->shapes.end()) { + if (nativeFields.empty()) { + return {}; + } + throw pybind11::value_error( + "schema declaration metadata is unavailable for " + m_name); + } + const auto& shapes = shapeIt->second; + if (shapes.size() != nativeFields.size()) { + throw pybind11::value_error( + "schema declaration metadata is inconsistent for " + m_name); + } + + std::vector fields; + fields.reserve(nativeFields.size()); + for (size_t index = 0; index < nativeFields.size(); ++index) { + const auto& field = nativeFields[index]; + const auto& shape = shapes[index]; + std::optional structName; + if (const auto* nested = field.GetStruct()) { + structName = nested->GetName(); + } + fields.emplace_back( + field.GetName(), FieldTypeName(field), field.GetSize(), + field.GetOffset(), field.GetArraySize(), field.GetBitWidth(), + field.GetBitShift(), field.GetBitMask(), field.GetEnumValues(), + std::move(structName), shape.isArray, shape.isBitField, shape.isEnum); + } + return fields; +} + +SchemaDatabase::SchemaDatabase() + : m_impl{std::make_shared()} {} + +SchemaDescriptor SchemaDatabase::Add(std::string_view name, + std::string_view schema) { + if (auto existing = m_impl->definitions.find(name); + existing != m_impl->definitions.end()) { + ParseSchema(schema); + ValidateArrayExtentsForPlatform(name, schema); + if (!SchemasEqual(existing->second, schema)) { + throw pybind11::value_error("conflicting schema for " + + std::string{name}); + } + return SchemaDescriptor{m_impl, std::string{name}}; + } + + auto staged = BuildStagedDatabase(m_impl, name, schema); + if (staged != m_impl) { + m_impl->database = std::move(staged->database); + m_impl->definitions = std::move(staged->definitions); + m_impl->shapes = std::move(staged->shapes); + } + return SchemaDescriptor{m_impl, std::string{name}}; +} + +SchemaDatabase SchemaDatabase::Stage(std::string_view name, + std::string_view schema) const { + SchemaDatabase staged; + staged.m_impl = BuildStagedDatabase(m_impl, name, schema); + return staged; +} + +std::optional SchemaDatabase::Find( + std::string_view name) const { + const auto* descriptor = m_impl->database->Find(name); + if (!descriptor) { + return std::nullopt; + } + return SchemaDescriptor{m_impl, descriptor->GetName()}; +} + +py::bytes PackSchema(const SchemaDescriptor& desc, const py::sequence& values) { + auto database = desc.m_impl->database; + const auto& descriptor = ResolveDescriptor(database, desc.m_name); + if (!descriptor.IsValid()) { + throw py::value_error("descriptor " + desc.m_name + " is not valid"); + } + + const auto& fields = descriptor.GetFields(); + if (values.size() != fields.size()) { + throw py::value_error("expected " + std::to_string(fields.size()) + + " fields, got " + std::to_string(values.size())); + } + + std::vector data(descriptor.GetSize(), 0); + wpi::util::MutableDynamicStruct output{&descriptor, data}; + for (size_t i = 0; i < fields.size(); ++i) { + PackField(output, fields[i], values[static_cast(i)]); + } + return {reinterpret_cast(data.data()), data.size()}; +} + +py::tuple UnpackSchema(const SchemaDescriptor& desc, const py::buffer& buffer) { + auto database = desc.m_impl->database; + const auto& descriptor = ResolveDescriptor(database, desc.m_name); + if (!descriptor.IsValid()) { + throw py::value_error("descriptor " + desc.m_name + " is not valid"); + } + + auto request = buffer.request(); + if (request.itemsize != 1) { + throw py::value_error("buffer must only contain bytes"); + } + if (request.ndim != 1) { + throw py::value_error("buffer must only have a single dimension"); + } + if (request.size != static_cast(descriptor.GetSize())) { + throw py::value_error("buffer must be " + + std::to_string(descriptor.GetSize()) + " bytes"); + } + if (request.strides[0] != 1) { + throw py::value_error("buffer must be contiguous"); + } + + std::span data{reinterpret_cast(request.ptr), + descriptor.GetSize()}; + wpi::util::DynamicStruct input{&descriptor, data}; + const auto& fields = descriptor.GetFields(); + py::tuple values{static_cast(fields.size())}; + for (size_t i = 0; i < fields.size(); ++i) { + values[static_cast(i)] = UnpackField(input, fields[i]); + } + return values; +} + +} // namespace wpy::structs diff --git a/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.h b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.h new file mode 100644 index 000000000..1585d9011 --- /dev/null +++ b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.h @@ -0,0 +1,69 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace py = pybind11; + +namespace wpy::structs { + +class SchemaDatabaseImpl; + +struct SchemaFieldDescriptor { + std::string name; + std::string type; + size_t size; + size_t offset; + size_t arraySize; + unsigned int bitWidth; + unsigned int bitShift; + uint64_t bitMask; + std::vector> enumValues; + std::optional structName; + bool isArray; + bool isBitField; + bool isEnum; +}; + +class SchemaDescriptor { + public: + std::string GetName() const; + std::string GetSchema() const; + bool IsValid() const; + size_t GetSize() const; + std::vector GetFields() const; + + private: + friend class SchemaDatabase; + friend py::bytes PackSchema(const SchemaDescriptor& desc, + const py::sequence& values); + friend py::tuple UnpackSchema(const SchemaDescriptor& desc, + const py::buffer& buffer); + SchemaDescriptor(std::shared_ptr impl, std::string name); + std::shared_ptr m_impl; + std::string m_name; +}; + +class SchemaDatabase { + public: + SchemaDatabase(); + SchemaDescriptor Add(std::string_view name, std::string_view schema); + SchemaDatabase Stage(std::string_view name, std::string_view schema) const; + std::optional Find(std::string_view name) const; + + private: + std::shared_ptr m_impl; +}; + +py::bytes PackSchema(const SchemaDescriptor& desc, const py::sequence& values); +py::tuple UnpackSchema(const SchemaDescriptor& desc, const py::buffer& buffer); + +} // namespace wpy::structs diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/__init__.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/__init__.py index 7d4af73d1..d4fc43e9f 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/__init__.py +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/__init__.py @@ -29,8 +29,12 @@ ] from .desc import StructDescriptor +from .layout import StructFieldLayout, StructLayout from .dataclass import ( + BitField, + CharArray, + char, make_wpistruct, int8, uint8, @@ -45,6 +49,11 @@ __all__ += [ "StructDescriptor", + "StructFieldLayout", + "StructLayout", + "BitField", + "CharArray", + "char", "make_wpistruct", "int8", "uint8", diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py new file mode 100644 index 000000000..2d13c1e72 --- /dev/null +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py @@ -0,0 +1,699 @@ +import collections.abc +import dataclasses +import enum +import inspect +import struct +import typing + +from .._wpiutil import wpistruct +from .._wpiutil._schema import SchemaDatabase, pack_schema, unpack_schema +from .dataclass import ( + BitField, + CharArray, + char, + double, + int8, + int16, + int32, + int64, + uint8, + uint16, + uint32, + uint64, +) +from .desc import StructDescriptor +from .layout import StructFieldLayout, StructLayout + +_type_to_fmt = { + bool: ("?", "bool"), + int8: ("b", "int8"), + uint8: ("B", "uint8"), + int16: ("h", "int16"), + uint16: ("H", "uint16"), + int: ("i", "int32"), + int32: ("i", "int32"), + uint32: ("I", "uint32"), + int64: ("q", "int64"), + uint64: ("Q", "uint64"), + float: ("f", "float"), + double: ("d", "double"), +} +_sized_integer_types = (int8, uint8, int16, uint16, int32, uint32, int64, uint64) +_signed_integer_types = (int8, int16, int32, int64) + + +@dataclasses.dataclass(slots=True) +class FieldPlan: + index: int + schema_name: str + python_name: str + annotation: type + element_type: type + is_array: bool + array_size: int + format: str | None + type_name: str + nested_type: type | None + bit_width: int | None = None + enum_type: type[enum.IntEnum] | None = None + enum_cache: dict[int, enum.IntEnum] = dataclasses.field(default_factory=dict) + is_char: bool = False + + +def _get_supported_type_names(): + supported_names = ", ".join(t.__name__ for t in _type_to_fmt.keys()) + return f"{supported_names}, or fixed-length homogeneous tuple of a supported type" + + +def _get_fixed_tuple_array_info(cls_name: str, field_name: str, field_type: type): + origin = typing.get_origin(field_type) + if origin is not tuple: + return None + + args = typing.get_args(field_type) + if not args or args[-1] is Ellipsis: + raise TypeError( + f"{cls_name}.{field_name} has unsupported tuple type hint: " + "tuple fields must be fixed-length and homogeneous" + ) from None + + element_type = args[0] + if not all(arg == element_type for arg in args): + raise TypeError( + f"{cls_name}.{field_name} has unsupported tuple type hint: " + "tuple fields must be fixed-length and homogeneous" + ) from None + + return element_type, len(args) + + +def _class_name(cls: type) -> str: + name_parts = [ + getattr(cls, "__module__", None), + getattr(cls, "__qualname__", cls.__name__), + ] + return ".".join(name for name in name_parts if name) + + +def _split_annotated(annotation: type): + if typing.get_origin(annotation) is typing.Annotated: + base_type, *metadata = typing.get_args(annotation) + return base_type, metadata + return annotation, [] + + +def _is_int_enum(field_type: type) -> bool: + return isinstance(field_type, type) and issubclass(field_type, enum.IntEnum) + + +def _integer_range(field_type: type, bit_width: int | None = None): + width = bit_width + if width is None: + width = struct.calcsize(_type_to_fmt[field_type][0]) * 8 + if field_type in _signed_integer_types: + return -(2 ** (width - 1)), 2 ** (width - 1) - 1 + return 0, 2**width - 1 + + +def _unsupported_field(cls_name: str, field_name: str): + raise TypeError( + f"{cls_name}.{field_name} is not a wpistruct or does not have a supported type hint " + f"(supported: {_get_supported_type_names()})" + ) from None + + +def _resolve_field_plan( + cls_name: str, + field_idx: int, + field_name: str, + annotation: type, + legacy_type: type, +) -> FieldPlan: + _, metadata = _split_annotated(annotation) + field_type = legacy_type + char_arrays = [item for item in metadata if isinstance(item, CharArray)] + bitfields = [item for item in metadata if isinstance(item, BitField)] + storage_types = [ + item + for item in metadata + if any(item is storage_type for storage_type in _sized_integer_types) + ] + + if len(char_arrays) > 1: + raise TypeError(f"{cls_name}.{field_name} has multiple CharArray metadata") + if len(bitfields) > 1: + raise TypeError(f"{cls_name}.{field_name} has multiple bitfield metadata") + if len(storage_types) > 1: + raise TypeError( + f"{cls_name}.{field_name} has multiple storage types for enum field" + ) + + bit_width = bitfields[0].width if bitfields else None + if char_arrays: + if field_type is not str: + raise TypeError( + f"{cls_name}.{field_name} CharArray metadata is only valid on str" + ) + if bit_width is not None: + raise TypeError(f"{cls_name}.{field_name} array cannot be bitfield") + if storage_types: + raise TypeError( + f"{cls_name}.{field_name} integer storage is only valid on enum fields" + ) + return FieldPlan( + index=field_idx, + schema_name=field_name, + python_name=field_name, + annotation=annotation, + element_type=str, + is_array=True, + array_size=char_arrays[0].size, + format=None, + type_name="char", + nested_type=None, + is_char=True, + ) + + array_info = _get_fixed_tuple_array_info(cls_name, field_name, field_type) + if array_info: + element_type, array_size = array_info + is_array = True + else: + element_type = field_type + array_size = 1 + is_array = False + + enum_type = element_type if _is_int_enum(element_type) else None + if enum_type is not None: + if not storage_types: + raise TypeError( + f"{cls_name}.{field_name} enum requires sized integer storage" + ) + storage_type = storage_types[0] + fmt, storage_name = _type_to_fmt[storage_type] + enum_values = ",".join( + f"{member_name}={member.value}" + for member_name, member in enum_type.__members__.items() + ) + type_name = f"enum {{{enum_values}}} {storage_name}" + nested_type = None + else: + if storage_types: + raise TypeError( + f"{cls_name}.{field_name} integer storage is only valid on enum fields" + ) + storage_type = element_type + if element_type in _type_to_fmt: + fmt, type_name = _type_to_fmt[element_type] + nested_type = None + elif hasattr(element_type, "WPIStruct"): + fmt = None + type_name = wpistruct.get_type_name(element_type) + nested_type = element_type + elif element_type is char and not is_array: + fmt = None + type_name = "char" + nested_type = None + else: + _unsupported_field(cls_name, field_name) + + if bit_width is not None: + if is_array: + raise TypeError(f"{cls_name}.{field_name} array cannot be bitfield") + if enum_type is not None: + bitfield_type = storage_type + else: + bitfield_type = element_type + if bitfield_type is bool: + if bit_width != 1: + raise TypeError( + f"{cls_name}.{field_name} bool bitfield width must be 1" + ) + elif bitfield_type in _sized_integer_types: + type_width = struct.calcsize(_type_to_fmt[bitfield_type][0]) * 8 + if bit_width > type_width: + raise TypeError( + f"{cls_name}.{field_name} bitfield width {bit_width} exceeds type size" + ) + else: + raise TypeError( + f"{cls_name}.{field_name} type {getattr(element_type, '__name__', element_type)} " + "cannot be bitfield" + ) + + if enum_type is not None: + minimum, maximum = _integer_range(storage_type, bit_width) + for member_name, member in enum_type.__members__.items(): + if member.value < minimum or member.value > maximum: + raise TypeError( + f"{cls_name}.{field_name} enum member {member_name}={member.value} " + f"does not fit storage range {minimum} to {maximum}" + ) + + return FieldPlan( + index=field_idx, + schema_name=field_name, + python_name=field_name, + annotation=annotation, + element_type=element_type, + is_array=is_array, + array_size=array_size, + format=fmt, + type_name=type_name, + nested_type=nested_type, + bit_width=bit_width, + enum_type=enum_type, + is_char=element_type is char, + ) + + +def _resolve_field_plans(cls: type, cls_name: str) -> list[FieldPlan]: + resolved_hints = typing.get_type_hints(cls, include_extras=True) + legacy_hints = typing.get_type_hints(cls) + return [ + _resolve_field_plan( + cls_name, + field_idx, + field.name, + resolved_hints[field.name], + legacy_hints[field.name], + ) + for field_idx, field in enumerate(dataclasses.fields(cls)) + ] + + +def _schema_for_plans(plans: list[FieldPlan]) -> str: + fields = [] + for plan in plans: + array_suffix = f"[{plan.array_size}]" if plan.is_array else "" + bitfield_suffix = f":{plan.bit_width}" if plan.bit_width is not None else "" + fields.append( + f"{plan.type_name} {plan.schema_name}{array_suffix}{bitfield_suffix}" + ) + return "; ".join(fields) + + +def _make_native_descriptor(struct_name: str, schema: str, plans: list[FieldPlan]): + database = SchemaDatabase() + schemas: dict[str, str] = {} + + def add_nested(type_string: str, nested_schema: str): + nested_name = type_string.removeprefix("struct:") + if schemas.get(nested_name) == nested_schema: + return + database.add(nested_name, nested_schema) + schemas[nested_name] = nested_schema + + for plan in plans: + if plan.nested_type is not None: + wpistruct.for_each_nested(plan.nested_type, add_nested) + + return database.add(struct_name, schema) + + +def _layout_python_names(native_fields, plans, python_names): + if python_names is None: + return tuple(plan.python_name for plan in plans) + if isinstance(python_names, collections.abc.Mapping): + return tuple(python_names[field.name] for field in native_fields) + return tuple(python_names) + + +def _make_layout(native_descriptor, plans, python_names) -> StructLayout: + native_fields = native_descriptor.fields + layout_names = _layout_python_names(native_fields, plans, python_names) + fields = tuple( + StructFieldLayout( + schema_name=field.name, + python_name=python_name, + type_name=field.type, + offset=field.offset, + size=field.size, + array_size=field.array_size, + bit_width=field.bit_width, + bit_shift=field.bit_shift, + bit_mask=field.bit_mask, + enum_values=tuple(field.enum_values), + nested_type=plan.nested_type, + ) + for field, plan, python_name in zip( + native_fields, plans, layout_names, strict=True + ) + ) + return StructLayout( + type_name=native_descriptor.name, + schema=native_descriptor.schema, + size=native_descriptor.size, + fields=fields, + ) + + +def _make_legacy_layout( + struct_name: str, schema: str, plans: list[FieldPlan] +) -> StructLayout: + offset = 0 + fields = [] + for plan in plans: + if plan.nested_type is not None: + field_size = wpistruct.get_size(plan.nested_type) + bit_width = 0 + bit_mask = 0 + else: + field_size = struct.calcsize(typing.cast(str, plan.format)) + bit_width = field_size * 8 + bit_mask = (1 << bit_width) - 1 + fields.append( + StructFieldLayout( + schema_name=plan.schema_name, + python_name=plan.python_name, + type_name=plan.type_name, + offset=offset, + size=field_size, + array_size=plan.array_size, + bit_width=bit_width, + bit_shift=0, + bit_mask=bit_mask, + enum_values=(), + nested_type=plan.nested_type, + ) + ) + offset += field_size * plan.array_size + return StructLayout( + type_name=struct_name, + schema=schema, + size=offset, + fields=tuple(fields), + ) + + +def _enum_from_int( + enum_type: type[enum.IntEnum], value: int, cache: dict[int, enum.IntEnum] +) -> enum.IntEnum: + member = enum_type._value2member_map_.get(value) + if member is not None: + return member + + member = cache.get(value) + if member is None: + member = int.__new__(enum_type, value) + member._name_ = f"UNKNOWN_{value}" + member._value_ = value + cache[value] = member + return member + + +def _descriptor_pack_element(plan: FieldPlan, value): + if plan.enum_type is not None: + if not isinstance(value, plan.enum_type): + raise TypeError( + f"field {plan.python_name} must be a {plan.enum_type.__name__} instance" + ) + return int(value) + if plan.nested_type is not None: + return wpistruct.pack(value) + return value + + +def _descriptor_pack_value(plan: FieldPlan, value): + if plan.is_char: + return value + if plan.is_array: + values = tuple(_descriptor_pack_element(plan, item) for item in value) + if len(values) != plan.array_size: + raise ValueError( + f"field {plan.python_name} must contain {plan.array_size} values" + ) + if plan.array_size == 1: + return values[0] + return values + return _descriptor_pack_element(plan, value) + + +def _descriptor_unpack_element(plan: FieldPlan, value): + if plan.enum_type is not None: + return _enum_from_int(plan.enum_type, value, plan.enum_cache) + if plan.nested_type is not None: + return wpistruct.unpack(plan.nested_type, value) + return value + + +def _descriptor_unpack_value(plan: FieldPlan, value): + if plan.is_char: + if plan.is_array: + return value + return char(value or "\0") + if plan.is_array: + values = (value,) if plan.array_size == 1 else value + return tuple(_descriptor_unpack_element(plan, item) for item in values) + return _descriptor_unpack_element(plan, value) + + +def _make_descriptor_serializer( + cls: type, + struct_name: str, + schema: str, + err_name: str, + plans: list[FieldPlan], + descriptor, +) -> StructDescriptor: + def pack_data(value): + values = tuple( + _descriptor_pack_value(plan, getattr(value, plan.python_name)) + for plan in plans + ) + return pack_schema(descriptor, values) + + def pack(value): + try: + return pack_data(value) + except Exception as exc: + raise ValueError(f"{err_name}: error packing data") from exc + + def pack_into(value, buffer): + try: + encoded = pack_data(value) + destination = memoryview(buffer).cast("B") + if destination.nbytes < len(encoded): + raise ValueError( + f"pack_into requires a buffer of at least {len(encoded)} bytes" + ) + destination[: len(encoded)] = encoded + except Exception as exc: + raise ValueError(f"{err_name}: error packing data") from exc + + def unpack(buffer): + try: + values = unpack_schema(descriptor, buffer) + converted = ( + _descriptor_unpack_value(plan, value) + for plan, value in zip(plans, values, strict=True) + ) + return cls(*converted) + except Exception as exc: + raise ValueError(f"{err_name}: error unpacking data") from exc + + nested_types = [plan.nested_type for plan in plans if plan.nested_type is not None] + if nested_types: + + def for_each_nested(fn): + try: + for nested_type in nested_types: + wpistruct.for_each_nested(nested_type, fn) + except Exception as exc: + raise ValueError(f"{err_name}: error in for_each_nested") from exc + + else: + for_each_nested = None + + return StructDescriptor( + typename=struct_name, + schema=schema, + size=descriptor.size, + pack=pack, + pack_into=pack_into, + unpack=unpack, + for_each_nested=for_each_nested, + ) + + +def compile_wpistruct( + cls, + struct_name, + *, + schema_override=None, + descriptor=None, + python_names=None, +) -> type: + cls_name = _class_name(cls) + if struct_name is None: + struct_name = cls.__name__ + err_name = cls_name + else: + err_name = f"{struct_name} ({cls_name})" + + plans = _resolve_field_plans(cls, cls_name) + schema = ( + schema_override if schema_override is not None else _schema_for_plans(plans) + ) + use_descriptor_codec = any( + plan.is_char or plan.enum_type is not None or plan.bit_width is not None + for plan in plans + ) + legacy_layout = None + if descriptor is None: + try: + descriptor = _make_native_descriptor(struct_name, schema, plans) + except UnicodeDecodeError: + if schema_override is not None or use_descriptor_codec: + raise + # The native parser accepts only ASCII identifiers, while legacy + # authored dataclasses have always accepted Python's Unicode + # identifiers. Their packed layout is the legacy struct.Struct + # layout, so construct equivalent immutable metadata without + # changing the public schema or serialization path. + legacy_layout = _make_legacy_layout(struct_name, schema, plans) + + if use_descriptor_codec: + serializer_descriptor = _make_descriptor_serializer( + cls, struct_name, schema, err_name, plans, descriptor + ) + layout = _make_layout(descriptor, plans, python_names) + cls.WPIStruct = serializer_descriptor + cls.__wpistruct_descriptor__ = layout + return cls + + fmts = [] + unpackvals = [] + cvvals = [] + vvals = [] + packs = [] + unpacks = [] + for_each_nested = [] + # Pack/unpack functions retain this globals dictionary, keeping the native + # descriptor database alive with the generated class. + ctx: dict[str, typing.Any] = { + "cls": cls, + "descriptor": descriptor, + "_err_name": err_name, + } + + for plan in plans: + name = plan.python_name + if plan.is_array: + argn = f"arg_{name}" + unpack_args = [ + f"arg{plan.index}_{item_idx}" for item_idx in range(plan.array_size) + ] + if plan.nested_type is None: + fmts.append(f"{plan.array_size}{plan.format}") + unpackvals.extend(unpack_args) + cvvals.append(argn) + vvals.append(f"*v.{name}") + unpacks.append(f"{argn} = ({', '.join(unpack_args)},)") + else: + typn = f"type_{name}" + ctx[typn] = plan.nested_type + size = wpistruct.get_size(plan.nested_type) + fmts.extend(f"{size}s" for _ in range(plan.array_size)) + unpackvals.extend(unpack_args) + vvals.append(f"*{argn}") + cvvals.append(argn) + packs.append(f"{argn} = tuple(wpistruct.pack(i) for i in v.{name})") + unpack_exprs = [ + f"wpistruct.unpack({typn}, {arg})" for arg in unpack_args + ] + unpacks.append(f"{argn} = ({', '.join(unpack_exprs)},)") + for_each_nested.append(f"wpistruct.for_each_nested({typn}, fn)") + elif plan.nested_type is not None: + argn = f"arg_{name}" + typn = f"type_{name}" + ctx[typn] = plan.nested_type + size = wpistruct.get_size(plan.nested_type) + fmts.append(f"{size}s") + vvals.append(argn) + unpackvals.append(argn) + cvvals.append(argn) + packs.append(f"{argn} = wpistruct.pack(v.{name})") + unpacks.append(f"{argn} = wpistruct.unpack({typn}, {argn})") + for_each_nested.append(f"wpistruct.for_each_nested({typn}, fn)") + else: + fmts.append(typing.cast(str, plan.format)) + unpackvals.append(f"arg_{name}") + cvvals.append(f"arg_{name}") + vvals.append(f"v.{name}") + + codec = struct.Struct(f"<{''.join(fmts)}") + unpack_values = ", ".join(unpackvals) + if len(unpackvals) == 1: + unpack_values += "," + if unpack_values: + unpack_statement = f"{unpack_values} = _s.unpack(b)" + else: + unpack_statement = "_s.unpack(b)" + constructor_values = ", ".join(cvvals) + values = ", ".join(vvals) + + padding = "\n" + " " * 16 + pack_statements = padding.join(packs) + unpack_statements = padding.join(unpacks) + + if not for_each_nested: + for_each_nested_statement = "_for_each_nested = None" + else: + for_each_nested_statement = "def _for_each_nested(fn):" + for_each_nested_statement += "\n" + " " * 12 + for_each_nested_statement += f"try:{padding}" + for_each_nested_statement += padding.join(for_each_nested) + for_each_nested_statement += "\n" + " " * 12 + for_each_nested_statement += "except Exception as e:" + for_each_nested_statement += f"{padding}raise ValueError(f'{{_err_name}}: error in for_each_nested') from e" + + ctx["_s"] = codec + function_source = inspect.cleandoc(f""" + from wpiutil import wpistruct + + def _pack(v): + try: + {pack_statements} + return _s.pack({values}) + except Exception as e: + raise ValueError(f"{{_err_name}}: error packing data") from e + + def _pack_into(v, b): + try: + {pack_statements} + return _s.pack_into(b, 0, {values}) + except Exception as e: + raise ValueError(f"{{_err_name}}: error packing data") from e + + def _unpack(b): + try: + {unpack_statement} + {unpack_statements} + return cls({constructor_values}) + except Exception as e: + raise ValueError(f"{{_err_name}}: error unpacking data") from e + + {for_each_nested_statement} + """) + exec(function_source, ctx, ctx) + + serializer_descriptor = StructDescriptor( + typename=struct_name, + schema=schema, + size=codec.size, + pack=ctx["_pack"], + pack_into=ctx["_pack_into"], + unpack=ctx["_unpack"], + for_each_nested=ctx["_for_each_nested"], + ) + + layout = ( + legacy_layout + if legacy_layout is not None + else _make_layout(descriptor, plans, python_names) + ) + + cls.WPIStruct = serializer_descriptor + cls.__wpistruct_descriptor__ = layout + return cls diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py new file mode 100644 index 000000000..14578aa57 --- /dev/null +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py @@ -0,0 +1,428 @@ +import dataclasses +import enum +import keyword +import re +import typing + +from .._wpiutil import wpistruct +from .._wpiutil._schema import SchemaDatabase +from ._compiler import compile_wpistruct +from .dataclass import ( + BitField, + CharArray, + char, + double, + int8, + int16, + int32, + int64, + uint8, + uint16, + uint32, + uint64, +) + + +class InvalidStructSchema(ValueError): + pass + + +class _UnresolvedStructSchema(ValueError): + def __init__(self, type_name: str): + self.type_name = type_name + super().__init__(f"nested struct type {type_name} is not registered") + + +_SPECIAL_ATTRIBUTE_NAMES = { + "__class__", + "__dict__", + "__weakref__", + "__dataclass_fields__", + "__dataclass_params__", + "__match_args__", +} + +_GENERATED_ATTRIBUTE_NAMES = { + "WPIStruct", + "__wpistruct_descriptor__", +} + +_PRIMITIVE_TYPES = { + "bool": bool, + "char": char, + "int8": int8, + "int16": int16, + "int32": int32, + "int64": int64, + "uint8": uint8, + "uint16": uint16, + "uint32": uint32, + "uint64": uint64, + "float": float, + "double": double, +} + +# Generated fixed arrays are represented as Python tuples and as fixed tuple +# annotations containing one type reference per element. A cumulative 65,536 +# elements caps each class's annotation pointer payload at 512 KiB on 64-bit +# CPython while leaving ample room for ordinary robotics sample arrays. Larger +# schemas remain valid WPILib grammar, but are not safely representable as +# generated Python classes. +_MAX_GENERATED_TUPLE_ELEMENTS = 65_536 + + +def _sanitize_identifier(value: str) -> str: + value = re.sub(r"\W", "_", value) + if not value: + value = "_" + if value[0].isdigit(): + value = f"_{value}" + if not value.isidentifier(): + identifier = "" + for character in value: + candidate = f"{identifier}{character}" + identifier += character if candidate.isidentifier() else "_" + value = identifier + if ( + keyword.iskeyword(value) + or value in _SPECIAL_ATTRIBUTE_NAMES + or hasattr(object, value) + ): + value = f"{value}_" + return value + + +def _unique_identifier(value: str, used: set[str]) -> str: + identifier = _sanitize_identifier(value) + if identifier not in used: + used.add(identifier) + return identifier + + suffix = 2 + separator = "" if identifier.endswith("_") else "_" + while f"{identifier}{separator}{suffix}" in used: + suffix += 1 + identifier = f"{identifier}{separator}{suffix}" + used.add(identifier) + return identifier + + +def _upper_first(value: str) -> str: + return f"{value[:1].upper()}{value[1:]}" + + +def _fixed_tuple(element_type: type, size: int): + return tuple[tuple(element_type for _ in range(size))] + + +def _is_enum_reserved_name(value: str) -> bool: + is_sunder = ( + len(value) > 2 + and value[0] == value[-1] == "_" + and value[1] != "_" + and value[-2] != "_" + ) + is_dunder = len(value) > 4 and value.startswith("__") and value.endswith("__") + return is_sunder or is_dunder + + +def _make_enum_type( + struct_name: str, field_name: str, enum_values, used_class_names: set[str] +): + class_name = _sanitize_identifier(struct_name.rsplit("::", 1)[-1]) + field_part = _upper_first(_sanitize_identifier(field_name)) + enum_name = _unique_identifier(f"{class_name}{field_part}", used_class_names) + used_names: set[str] = set() + members = [] + for member_name, value in enum_values: + member_name = _sanitize_identifier(member_name) + if member_name == "mro": + member_name = "mro_" + elif _is_enum_reserved_name(member_name): + member_name = f"{member_name}member" + member_name = _unique_identifier(member_name, used_names) + members.append((member_name, value)) + return enum.IntEnum(enum_name, members, module=__name__) + + +def _field_annotation( + struct_name: str, + field, + python_name: str, + nested, + used_enum_names: set[str], +): + is_array = field.is_array + + if field.struct_name is not None: + try: + annotation = nested[field.struct_name] + except KeyError: + raise _UnresolvedStructSchema(field.struct_name) from None + metadata = [] + elif field.is_enum: + annotation = _make_enum_type( + struct_name, python_name, field.enum_values, used_enum_names + ) + metadata = [_PRIMITIVE_TYPES[field.type]] + else: + annotation = _PRIMITIVE_TYPES[field.type] + metadata = [] + + if annotation is char and is_array: + return typing.Annotated[str, CharArray(field.array_size)] + + if is_array: + annotation = _fixed_tuple(annotation, field.array_size) + if field.is_bit_field: + metadata.append(BitField(field.bit_width)) + if metadata: + annotation = typing.Annotated[annotation, *metadata] + return annotation + + +def _schema_operation(operation, type_name: str, schema: str): + try: + return operation(type_name, schema) + except UnicodeDecodeError as exc: + raise InvalidStructSchema(f"parse error: {exc}") from exc + except ValueError as exc: + if str(exc).startswith("parse error:"): + raise InvalidStructSchema(str(exc)) from exc + raise + + +def _add_schema(database: SchemaDatabase, type_name: str, schema: str): + return _schema_operation(database.add, type_name, schema) + + +def _stage_schema(database: SchemaDatabase, type_name: str, schema: str): + return _schema_operation(database.stage, type_name, schema) + + +def _native_seed_schema(struct_type: type) -> str: + layout = struct_type.__wpistruct_descriptor__ + declarations = [] + for index, field in enumerate(layout.fields): + if field.enum_values: + values = ",".join(f"{name}={value}" for name, value in field.enum_values) + type_name = f"enum {{{values}}} {field.type_name}" + else: + type_name = field.type_name + array_suffix = f"[{field.array_size}]" if field.array_size > 1 else "" + is_bitfield = field.nested_type is None and ( + field.bit_shift != 0 or field.bit_width != field.size * 8 + ) + bitfield_suffix = f":{field.bit_width}" if is_bitfield else "" + declarations.append(f"{type_name} field{index}{array_suffix}{bitfield_suffix}") + return "; ".join(declarations) + + +def _add_nested_dependency_schemas( + database: SchemaDatabase, + descriptor, + nested: typing.Mapping[str, type], +) -> None: + definitions = {} + + def add_nested(type_string: str, schema: str): + type_name = type_string.removeprefix("struct:") + previous = definitions.get(type_name) + if previous == schema: + return + + try: + database.add(type_name, schema) + effective_schema = schema + except UnicodeDecodeError: + struct_type = nested.get(type_name) + if struct_type is None or not hasattr( + struct_type, "__wpistruct_descriptor__" + ): + raise + effective_schema = _native_seed_schema(struct_type) + try: + database.add(type_name, effective_schema) + except UnicodeDecodeError: + # A Unicode type name cannot be referenced by raw native schema + # grammar. The unresolved candidate reports the type name below. + return + definitions[type_name] = effective_schema + + required_names = { + field.struct_name + for field in descriptor.fields + if field.struct_name is not None + } + for type_name in required_names: + nested_type = nested.get(type_name) + if nested_type is not None: + wpistruct.for_each_nested(nested_type, add_nested) + + +def _make_candidate_descriptor( + name: str, schema: str, nested: typing.Mapping[str, type] +): + database = SchemaDatabase() + descriptor = _add_schema(database, name, schema) + if not descriptor.is_valid: + _add_nested_dependency_schemas(database, descriptor, nested) + return descriptor + + +def _validate_equivalent_schema( + name: str, existing_schema: str, candidate_schema: str +) -> None: + database = SchemaDatabase() + _add_schema(database, name, existing_schema) + _stage_schema(database, name, candidate_schema) + + +def make_wpistruct_from_schema( + name: str, + schema: str, + *, + nested: typing.Mapping[str, type], + descriptor=None, +) -> type: + if descriptor is None: + descriptor = _make_candidate_descriptor(name, schema, nested) + + if not descriptor.is_valid: + missing = next( + ( + field.struct_name + for field in descriptor.fields + if field.struct_name is not None and field.struct_name not in nested + ), + None, + ) + if missing is not None: + raise _UnresolvedStructSchema(missing) + raise ValueError(f"descriptor {name} is not valid") + + class_name = _sanitize_identifier(name.rsplit("::", 1)[-1]) + used_names: set[str] = set() + fields = [] + python_names = [] + used_enum_names: set[str] = set() + generated_tuple_elements = 0 + for field in descriptor.fields: + if field.type != "char" and field.is_array: + generated_tuple_elements += field.array_size + if generated_tuple_elements > _MAX_GENERATED_TUPLE_ELEMENTS: + raise ValueError( + "generated wpistruct arrays contain " + f"{generated_tuple_elements} total elements; support at most " + f"{_MAX_GENERATED_TUPLE_ELEMENTS}" + ) + + field_name = field.name + if field_name in _GENERATED_ATTRIBUTE_NAMES: + field_name = f"{field_name}_" + python_name = _unique_identifier(field_name, used_names) + annotation = _field_annotation( + name, field, python_name, nested, used_enum_names + ) + fields.append((python_name, annotation)) + python_names.append(python_name) + + generated = dataclasses.make_dataclass( + class_name, + fields, + ) + generated = compile_wpistruct( + generated, + name, + schema_override=schema, + descriptor=descriptor, + python_names=python_names, + ) + for field in dataclasses.fields(generated): + annotation = field.type + if typing.get_origin(annotation) is typing.Annotated: + field.type = typing.get_args(annotation)[0] + return generated + + +class StructTypeRegistry: + def __init__(self, struct_types: typing.Iterable[type]): + self._types: dict[str, type] = {} + self._definitions: dict[str, str] = {} + self._supplied_names: set[str] = set() + + supplied_types = tuple(struct_types) + for struct_type in supplied_types: + type_name = wpistruct.get_type_name(struct_type) + existing = self._types.get(type_name) + if existing is not None and existing is not struct_type: + raise ValueError(f"duplicate supplied struct type {type_name}") + self._types[type_name] = struct_type + self._supplied_names.add(type_name) + + seed_types: dict[str, type] = {} + + def collect_seed_types(struct_type: type) -> None: + type_name = wpistruct.get_type_name(struct_type) + if type_name in seed_types: + return + seed_types[type_name] = struct_type + layout = getattr(struct_type, "__wpistruct_descriptor__", None) + if layout is not None: + for field in layout.fields: + if field.nested_type is not None: + collect_seed_types(field.nested_type) + + for struct_type in supplied_types: + collect_seed_types(struct_type) + + seed_database = SchemaDatabase() + + def add_nested(type_string: str, schema: str): + type_name = type_string.removeprefix("struct:") + try: + seed_database.add(type_name, schema) + effective_schema = schema + except UnicodeDecodeError: + struct_type = seed_types.get(type_name) + if struct_type is None or not hasattr( + struct_type, "__wpistruct_descriptor__" + ): + raise + effective_schema = _native_seed_schema(struct_type) + try: + seed_database.add(type_name, effective_schema) + except UnicodeDecodeError: + # A Unicode type name cannot be referenced by raw native + # schema grammar. Supplied-type lookup still preserves the + # authored type's exact public schema and serialization. + return + self._definitions.setdefault(type_name, effective_schema) + + for struct_type in supplied_types: + wpistruct.for_each_nested(struct_type, add_nested) + + def get(self, type_name: str) -> type | None: + return self._types.get(type_name) + + def add_schema(self, type_name: str, schema: str) -> type: + if type_name in self._supplied_names: + return self._types[type_name] + + existing_schema = self._definitions.get(type_name) + if existing_schema is not None: + _validate_equivalent_schema(type_name, existing_schema, schema) + + existing = self._types.get(type_name) + if existing is not None: + return existing + + generated = make_wpistruct_from_schema( + type_name, + schema, + nested=self._types, + ) + + self._definitions[type_name] = schema + self._types[type_name] = generated + return generated diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/dataclass.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/dataclass.py index 6a24b09a7..7debdcda5 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/dataclass.py +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/dataclass.py @@ -1,19 +1,13 @@ import dataclasses -import inspect -import struct import typing - -from .desc import StructDescriptor -from .._wpiutil import wpistruct - # # Use these types to specify explicitly sized integers, but you can # also use int/bool/float # # fmt: off - + if typing.TYPE_CHECKING: int8 = int uint8 = int @@ -39,6 +33,41 @@ class double(float): pass # fmt: on +class char(str): + def __new__(cls, value: str, /): + if not isinstance(value, str): + raise TypeError("char value must be str") + if len(value.encode("utf-8")) != 1: + raise ValueError("char value must occupy exactly one UTF-8 byte") + return super().__new__(cls, value) + + +@dataclasses.dataclass(frozen=True, slots=True) +class CharArray: + size: int + + def __post_init__(self): + if ( + isinstance(self.size, bool) + or not isinstance(self.size, int) + or self.size <= 0 + ): + raise ValueError("CharArray size must be a positive integer") + + +@dataclasses.dataclass(frozen=True, slots=True) +class BitField: + width: int + + def __post_init__(self): + if ( + isinstance(self.width, bool) + or not isinstance(self.width, int) + or self.width <= 0 + ): + raise ValueError("BitField width must be a positive integer") + + def make_wpistruct(cls=None, /, *, name: str | None = None): """ This decorator allows you to easily define a custom type that can be @@ -63,235 +92,11 @@ class MyStruct: """ def wrap(cls): - return _process_class(cls, name) + from ._compiler import compile_wpistruct + + return compile_wpistruct(cls, name) if cls is None: return wrap return wrap(cls) - - -# -# Internals -# - -_type_to_fmt = { - bool: ("?", "bool"), - int8: ("b", "int8"), - uint8: ("B", "uint8"), - int16: ("h", "int16"), - uint16: ("H", "uint16"), - int: ("i", "int32"), - int32: ("i", "int32"), - uint32: ("I", "uint32"), - int64: ("q", "int64"), - uint64: ("Q", "uint64"), - float: ("f", "float"), - double: ("d", "double"), -} - - -def _get_supported_type_names(): - supported_names = ", ".join(t.__name__ for t in _type_to_fmt.keys()) - return f"{supported_names}, or fixed-length homogeneous tuple of a supported type" - - -def _get_fixed_tuple_array_info(cls_name: str, field_name: str, ftype: type): - origin = typing.get_origin(ftype) - if origin is not tuple: - return None - - args = typing.get_args(ftype) - if not args or args[-1] is Ellipsis: - raise TypeError( - f"{cls_name}.{field_name} has unsupported tuple type hint: " - "tuple fields must be fixed-length and homogeneous" - ) from None - - element_type = args[0] - if not all(arg == element_type for arg in args): - raise TypeError( - f"{cls_name}.{field_name} has unsupported tuple type hint: " - "tuple fields must be fixed-length and homogeneous" - ) from None - - return element_type, len(args) - - -def _process_class(cls, struct_name: str | None): - resolved_hints = typing.get_type_hints(cls) - field_names = [field.name for field in dataclasses.fields(cls)] - resolved_field_types = {name: resolved_hints[name] for name in field_names} - - name_parts = [] - name_parts.append(getattr(cls, "__module__", None)) - name_parts.append(getattr(cls, "__qualname__", cls.__name__)) - cls_name = ".".join([n for n in name_parts if n]) - - if struct_name is None: - struct_name = cls.__name__ - err_name = cls_name - else: - err_name = f"{struct_name} ({cls_name})" - - fmts = [] - schema = [] - unpackvals = [] - cvvals = [] - vvals = [] - packs = [] - unpacks = [] - # unpack_intos = [] - for_each_nested = [] - - ctx: dict[str, typing.Any] = {"cls": cls} - - for field_idx, (name, ftype) in enumerate(resolved_field_types.items()): - if ftype in _type_to_fmt: - fmt, stype = _type_to_fmt[ftype] - - fmts.append(fmt) - schema.append(f"{stype} {name}") - unpackvals.append(f"arg_{name}") - cvvals.append(f"arg_{name}") - vvals.append(f"v.{name}") - - elif array_info := _get_fixed_tuple_array_info(cls_name, name, ftype): - element_type, array_len = array_info - argn = f"arg_{name}" - unpack_args = [f"arg{field_idx}_{i}" for i in range(array_len)] - - if element_type in _type_to_fmt: - fmt, stype = _type_to_fmt[element_type] - - fmts.append(f"{array_len}{fmt}") - schema.append(f"{stype} {name}[{array_len}]") - unpackvals.extend(unpack_args) - cvvals.append(argn) - vvals.append(f"*v.{name}") - unpacks.append(f"{argn} = ({', '.join(unpack_args)},)") - - elif hasattr(element_type, "WPIStruct"): - typn = f"type_{name}" - - ctx[typn] = element_type - ts = wpistruct.get_type_name(element_type) - schema.append(f"{ts} {name}[{array_len}]") - sz = wpistruct.get_size(element_type) - fmts.extend(f"{sz}s" for _ in range(array_len)) - unpackvals.extend(unpack_args) - vvals.append(f"*{argn}") - cvvals.append(argn) - packs.append(f"{argn} = tuple(wpistruct.pack(i) for i in v.{name})") - unpack_exprs = [f"wpistruct.unpack({typn}, {a})" for a in unpack_args] - unpacks.append(f"{argn} = ({', '.join(unpack_exprs)},)") - # unpack_intos.append(f"wpistruct.unpack_into(v.{name}, {argn})") - for_each_nested.append(f"wpistruct.for_each_nested({typn}, fn)") - - else: - raise TypeError( - f"{cls_name}.{name} is not a wpistruct or does not have a supported type hint " - f"(supported: {_get_supported_type_names()})" - ) from None - - elif hasattr(ftype, "WPIStruct"): - # nested struct - argn = f"arg_{name}" - typn = f"type_{name}" - - ctx[typn] = ftype - ts = wpistruct.get_type_name(ftype) - schema.append(f"{ts} {name}") - sz = wpistruct.get_size(ftype) - fmts.append(f"{sz}s") - vvals.append(argn) - unpackvals.append(argn) - cvvals.append(argn) - packs.append(f"{argn} = wpistruct.pack(v.{name})") - unpacks.append(f"{argn} = wpistruct.unpack({typn}, {argn})") - # unpack_intos.append(f"wpistruct.unpack_into(v.{name}, {argn})") - for_each_nested.append(f"wpistruct.for_each_nested({typn}, fn)") - - else: - raise TypeError( - f"{cls_name}.{name} is not a wpistruct or does not have a supported type hint " - f"(supported: {_get_supported_type_names()})" - ) from None - - s = struct.Struct(f"<{''.join(fmts)}") - uvals = ", ".join(unpackvals) - if len(unpackvals) == 1: - uvals += "," - cvals = ", ".join(cvvals) - vals = ", ".join(vvals) - - padding = "\n" + " " * 16 - pack_stmts = padding.join(packs) - unpack_stmts = padding.join(unpacks) - # unpack_into_stmts = padding.join(unpack_intos) - - if not for_each_nested: - for_each_nested_stmt = "_for_each_nested = None" - else: - for_each_nested_stmt = f"def _for_each_nested(fn):" - for_each_nested_stmt += "\n" + " " * 12 - for_each_nested_stmt += f"try:{padding}" - for_each_nested_stmt += padding.join(for_each_nested) - for_each_nested_stmt += "\n" + " " * 12 - for_each_nested_stmt += f"except Exception as e:" - for_each_nested_stmt += ( - f"{padding}raise ValueError(f'{err_name}: error in for_each_nested') from e" - ) - - ctx["_s"] = s - - # Construct the serialization functions using the same hack NamedTuple uses - fnsrc = inspect.cleandoc(f""" - from wpiutil import wpistruct - - def _pack(v): - try: - {pack_stmts} - return _s.pack({vals}) - except Exception as e: - raise ValueError(f"{err_name}: error packing data") from e - - def _pack_into(v, b): - try: - {pack_stmts} - return _s.pack_into(b, 0, {vals}) - except Exception as e: - raise ValueError(f"{err_name}: error packing data") from e - - def _unpack(b): - try: - {uvals} = _s.unpack(b) - {unpack_stmts} - return cls({cvals}) - except Exception as e: - raise ValueError(f"{err_name}: error unpacking data") from e - - #def _unpack_into(v, b): - # try: - # {vals} = _s.unpack(b) - # {{unpack_into_stmts}} - # except Exception as e: - # raise ValueError(f"{err_name}: error unpacking data") from e - - {for_each_nested_stmt} - """) - - exec(fnsrc, ctx, ctx) - - cls.WPIStruct = StructDescriptor( - typename=struct_name, - schema="; ".join(schema), - size=s.size, - pack=ctx["_pack"], - pack_into=ctx["_pack_into"], - unpack=ctx["_unpack"], - # unpack_into=ctx["_unpack_into"], - for_each_nested=ctx["_for_each_nested"], - ) - - return cls diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/desc.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/desc.py index e53d83529..ce7d7d61c 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/desc.py +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/desc.py @@ -8,6 +8,12 @@ class StructDescriptor(typing.NamedTuple): have an attribute `WPIStruct` that contains this class (but C++ classes do not have this). + ``WPIStruct`` remains the serializer descriptor used by the native + serialization functions. Classes created by + :func:`wpiutil.wpistruct.make_wpistruct` also have a + ``__wpistruct_descriptor__`` attribute containing parsed field and layout + metadata. + It is not intended that you should create this class directly, something else should generate it for you. diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/layout.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/layout.py new file mode 100644 index 000000000..42d970abc --- /dev/null +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/layout.py @@ -0,0 +1,24 @@ +import dataclasses + + +@dataclasses.dataclass(frozen=True, slots=True) +class StructFieldLayout: + schema_name: str + python_name: str + type_name: str + offset: int + size: int + array_size: int + bit_width: int + bit_shift: int + bit_mask: int + enum_values: tuple[tuple[str, int], ...] + nested_type: type | None + + +@dataclasses.dataclass(frozen=True, slots=True) +class StructLayout: + type_name: str + schema: str + size: int + fields: tuple[StructFieldLayout, ...] From 47a5a0ff8e1cc846fadb9b49282253950802ba38 Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Mon, 17 Aug 2026 03:14:18 +0000 Subject: [PATCH 02/14] refactor(wpiutil): remove unicode schema fallback --- .../tests/test_schema_bridge.py | 14 ++++ .../tests/test_struct_annotations.py | 48 +++++++------- .../tests/test_struct_schema.py | 16 +++-- .../wpiutil/wpistruct/_compiler.py | 65 ++----------------- 4 files changed, 56 insertions(+), 87 deletions(-) diff --git a/subprojects/robotpy-wpiutil/tests/test_schema_bridge.py b/subprojects/robotpy-wpiutil/tests/test_schema_bridge.py index ca824b43b..b5d9cedb0 100644 --- a/subprojects/robotpy-wpiutil/tests/test_schema_bridge.py +++ b/subprojects/robotpy-wpiutil/tests/test_schema_bridge.py @@ -25,6 +25,20 @@ def test_schema_descriptor_metadata(): assert desc.fields[1].bit_mask == 0x7 +def test_schema_database_accepts_utf8_identifiers(): + database = SchemaDatabase() + nested = database.add("温度类型", "uint16 变量") + descriptor = database.add("UnicodePacket", "int32 é; 温度类型 π") + + assert nested.name == "温度类型" + assert nested.schema == "uint16 变量" + assert nested.fields[0].name == "变量" + assert descriptor.schema == "int32 é; 温度类型 π" + assert [field.name for field in descriptor.fields] == ["é", "π"] + assert descriptor.fields[1].struct_name == "温度类型" + assert descriptor.size == 6 + + def test_schema_descriptor_nested_delayed_validity(): db = SchemaDatabase() outer = db.add("Outer", "Inner value") diff --git a/subprojects/robotpy-wpiutil/tests/test_struct_annotations.py b/subprojects/robotpy-wpiutil/tests/test_struct_annotations.py index 46588e8f0..4428f7044 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct_annotations.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct_annotations.py @@ -23,20 +23,22 @@ def test_metadata_marker_validation(): wpistruct.BitField(-1) -@wpistruct.make_wpistruct(name="Legacy") +@wpistruct.make_wpistruct(name="AuthoredStruct") @dataclasses.dataclass -class Legacy: +class AuthoredStruct: count: int values: tuple[wpistruct.uint16, wpistruct.uint16] -def test_legacy_schema_and_bytes_remain_exact(): - assert wpistruct.get_schema(Legacy) == "int32 count; uint16 values[2]" - assert wpistruct.pack(Legacy(1, (2, 3))) == b"\x01\0\0\0\x02\0\x03\0" - assert wpistruct.unpack(Legacy, b"\x01\0\0\0\x02\0\x03\0") == Legacy(1, (2, 3)) +def test_authored_schema_and_bytes_remain_exact(): + assert wpistruct.get_schema(AuthoredStruct) == "int32 count; uint16 values[2]" + assert wpistruct.pack(AuthoredStruct(1, (2, 3))) == b"\x01\0\0\0\x02\0\x03\0" + assert wpistruct.unpack( + AuthoredStruct, b"\x01\0\0\0\x02\0\x03\0" + ) == AuthoredStruct(1, (2, 3)) -def test_legacy_singleton_tuple_remains_an_array(): +def test_authored_singleton_tuple_remains_an_array(): @wpistruct.make_wpistruct @dataclasses.dataclass class SingletonTuple: @@ -48,7 +50,7 @@ class SingletonTuple: assert wpistruct.unpack(SingletonTuple, b"\x08") == SingletonTuple((8,)) -def test_legacy_annotated_metadata_uses_base_type(): +def test_authored_annotated_metadata_uses_base_type(): @wpistruct.make_wpistruct @dataclasses.dataclass class AnnotatedValue: @@ -59,7 +61,7 @@ class AnnotatedValue: assert wpistruct.unpack(AnnotatedValue, wpistruct.pack(value)) == value -def test_legacy_tuple_element_annotated_metadata_uses_base_type(): +def test_authored_tuple_element_annotated_metadata_uses_base_type(): @wpistruct.make_wpistruct @dataclasses.dataclass class AnnotatedTuple: @@ -70,7 +72,7 @@ class AnnotatedTuple: assert wpistruct.unpack(AnnotatedTuple, wpistruct.pack(value)) == value -def test_legacy_metadata_equality_is_not_evaluated(): +def test_authored_metadata_equality_is_not_evaluated(): class ApplicationMetadata: def __eq__(self, other): raise AssertionError("application metadata equality was evaluated") @@ -99,8 +101,8 @@ class InvalidSchema: def test_compiler_attaches_parsed_layout_metadata(): - assert Legacy.__wpistruct_descriptor__ == wpistruct.StructLayout( - type_name="Legacy", + assert AuthoredStruct.__wpistruct_descriptor__ == wpistruct.StructLayout( + type_name="AuthoredStruct", schema="int32 count; uint16 values[2]", size=8, fields=( @@ -134,9 +136,9 @@ def test_compiler_attaches_parsed_layout_metadata(): ) -def test_legacy_unicode_field_names_preserve_schema_bytes_and_layout(): +def test_authored_unicode_field_names_preserve_schema_bytes_and_layout(): unicode_struct = dataclasses.make_dataclass( - "LegacyUnicode", + "AuthoredUnicode", [ ("é", wpistruct.int32), ("π", wpistruct.uint16), @@ -144,7 +146,7 @@ def test_legacy_unicode_field_names_preserve_schema_bytes_and_layout(): ("aé", wpistruct.int8), ], ) - unicode_struct = wpistruct.make_wpistruct(name="LegacyUnicode")(unicode_struct) + unicode_struct = wpistruct.make_wpistruct(name="AuthoredUnicode")(unicode_struct) value = unicode_struct(-2, 0x1234, True, -3) encoded = b"\xfe\xff\xff\xff\x34\x12\x01\xfd" @@ -162,7 +164,7 @@ def test_legacy_unicode_field_names_preserve_schema_bytes_and_layout(): ] == [("é", "é"), ("π", "π"), ("变量", "变量"), ("aé", "aé")] -def test_nested_legacy_unicode_fields_preserve_public_behavior(): +def test_nested_authored_unicode_fields_preserve_public_behavior(): inner = dataclasses.make_dataclass("UnicodeInner", [("变量", wpistruct.uint16)]) inner = wpistruct.make_wpistruct(name="UnicodeInner")(inner) outer = dataclasses.make_dataclass( @@ -288,17 +290,17 @@ class AuthoredSingletonArrays: initial: wpistruct.char samples: tuple[wpistruct.uint8] modes: Annotated[tuple[Mode], wpistruct.uint8] - nested: tuple[Legacy] + nested: tuple[AuthoredStruct] def test_descriptor_codec_preserves_authored_singleton_tuple_semantics(): value = AuthoredSingletonArrays( - wpistruct.char("A"), (7,), (Mode.AUTO,), (Legacy(2, (3, 4)),) + wpistruct.char("A"), (7,), (Mode.AUTO,), (AuthoredStruct(2, (3, 4)),) ) assert wpistruct.get_schema(AuthoredSingletonArrays) == ( "char initial; uint8 samples[1]; " - "enum {OFF=0,AUTO=1,DEFAULT=1} uint8 modes[1]; Legacy nested[1]" + "enum {OFF=0,AUTO=1,DEFAULT=1} uint8 modes[1]; AuthoredStruct nested[1]" ) assert wpistruct.pack(value) == b"A\x07\x01\x02\0\0\0\x03\0\x04\0" assert wpistruct.unpack(AuthoredSingletonArrays, wpistruct.pack(value)) == value @@ -309,14 +311,14 @@ def test_descriptor_codec_preserves_authored_singleton_tuple_semantics(): class AuthoredDescriptorArrays: samples: tuple[wpistruct.uint16, wpistruct.uint16] modes: Annotated[tuple[Mode, Mode], wpistruct.uint8] - nested: tuple[Legacy, Legacy] + nested: tuple[AuthoredStruct, AuthoredStruct] def test_descriptor_codec_authored_arrays_larger_than_one_have_literal_layout(): value = AuthoredDescriptorArrays( (0x1234, 0xABCD), (Mode.OFF, Mode.AUTO), - (Legacy(1, (2, 3)), Legacy(-1, (4, 5))), + (AuthoredStruct(1, (2, 3)), AuthoredStruct(-1, (4, 5))), ) encoded = ( b"\x34\x12\xcd\xab\x00\x01" @@ -326,7 +328,7 @@ def test_descriptor_codec_authored_arrays_larger_than_one_have_literal_layout(): assert wpistruct.get_schema(AuthoredDescriptorArrays) == ( "uint16 samples[2]; " - "enum {OFF=0,AUTO=1,DEFAULT=1} uint8 modes[2]; Legacy nested[2]" + "enum {OFF=0,AUTO=1,DEFAULT=1} uint8 modes[2]; AuthoredStruct nested[2]" ) assert wpistruct.pack(value) == encoded assert wpistruct.unpack(AuthoredDescriptorArrays, encoded) == value @@ -473,7 +475,7 @@ class TooWideForSignedBitfield(enum.IntEnum): [ (Annotated[float, wpistruct.BitField(1)], "cannot be bitfield"), (Annotated[wpistruct.char, wpistruct.BitField(1)], "cannot be bitfield"), - (Annotated[Legacy, wpistruct.BitField(1)], "cannot be bitfield"), + (Annotated[AuthoredStruct, wpistruct.BitField(1)], "cannot be bitfield"), (Annotated[bool, wpistruct.BitField(2)], "width must be 1"), ( Annotated[wpistruct.int16, wpistruct.BitField(17)], diff --git a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py index c14672eb5..0caf006f2 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py @@ -431,11 +431,17 @@ def test_direct_generation_preserves_schema_error_taxonomy(): assert type(exc_info.value) is exception_type -def test_non_ascii_parser_failures_preserve_schema_error_taxonomy(): - with pytest.raises(InvalidStructSchema): - make_wpistruct_from_schema("Bad", "uint8 é", nested={}) - with pytest.raises(InvalidStructSchema): - StructTypeRegistry(()).add_schema("Bad", "uint8 é") +def test_generated_and_registry_schemas_accept_authored_unicode_identifier(): + schema = "uint8 é" + generated = make_wpistruct_from_schema("DirectAuthoredUnicode", schema, nested={}) + registered = StructTypeRegistry(()).add_schema("RegistryAuthoredUnicode", schema) + + for struct_type in (generated, registered): + assert [field.name for field in dataclasses.fields(struct_type)] == ["é"] + assert wpistruct.get_schema(struct_type) == schema + value = struct_type(7) + assert wpistruct.pack(value) == b"\x07" + assert wpistruct.unpack(struct_type, b"\x07") == value def test_registry_accepts_supplied_nested_unicode_authored_structs(): diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py index 2d13c1e72..5976c9a0f 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py @@ -127,10 +127,10 @@ def _resolve_field_plan( field_idx: int, field_name: str, annotation: type, - legacy_type: type, + base_type: type, ) -> FieldPlan: _, metadata = _split_annotated(annotation) - field_type = legacy_type + field_type = base_type char_arrays = [item for item in metadata if isinstance(item, CharArray)] bitfields = [item for item in metadata if isinstance(item, BitField)] storage_types = [ @@ -269,14 +269,14 @@ def _resolve_field_plan( def _resolve_field_plans(cls: type, cls_name: str) -> list[FieldPlan]: resolved_hints = typing.get_type_hints(cls, include_extras=True) - legacy_hints = typing.get_type_hints(cls) + base_hints = typing.get_type_hints(cls) return [ _resolve_field_plan( cls_name, field_idx, field.name, resolved_hints[field.name], - legacy_hints[field.name], + base_hints[field.name], ) for field_idx, field in enumerate(dataclasses.fields(cls)) ] @@ -348,44 +348,6 @@ def _make_layout(native_descriptor, plans, python_names) -> StructLayout: ) -def _make_legacy_layout( - struct_name: str, schema: str, plans: list[FieldPlan] -) -> StructLayout: - offset = 0 - fields = [] - for plan in plans: - if plan.nested_type is not None: - field_size = wpistruct.get_size(plan.nested_type) - bit_width = 0 - bit_mask = 0 - else: - field_size = struct.calcsize(typing.cast(str, plan.format)) - bit_width = field_size * 8 - bit_mask = (1 << bit_width) - 1 - fields.append( - StructFieldLayout( - schema_name=plan.schema_name, - python_name=plan.python_name, - type_name=plan.type_name, - offset=offset, - size=field_size, - array_size=plan.array_size, - bit_width=bit_width, - bit_shift=0, - bit_mask=bit_mask, - enum_values=(), - nested_type=plan.nested_type, - ) - ) - offset += field_size * plan.array_size - return StructLayout( - type_name=struct_name, - schema=schema, - size=offset, - fields=tuple(fields), - ) - - def _enum_from_int( enum_type: type[enum.IntEnum], value: int, cache: dict[int, enum.IntEnum] ) -> enum.IntEnum: @@ -539,19 +501,8 @@ def compile_wpistruct( plan.is_char or plan.enum_type is not None or plan.bit_width is not None for plan in plans ) - legacy_layout = None if descriptor is None: - try: - descriptor = _make_native_descriptor(struct_name, schema, plans) - except UnicodeDecodeError: - if schema_override is not None or use_descriptor_codec: - raise - # The native parser accepts only ASCII identifiers, while legacy - # authored dataclasses have always accepted Python's Unicode - # identifiers. Their packed layout is the legacy struct.Struct - # layout, so construct equivalent immutable metadata without - # changing the public schema or serialization path. - legacy_layout = _make_legacy_layout(struct_name, schema, plans) + descriptor = _make_native_descriptor(struct_name, schema, plans) if use_descriptor_codec: serializer_descriptor = _make_descriptor_serializer( @@ -688,11 +639,7 @@ def _unpack(b): for_each_nested=ctx["_for_each_nested"], ) - layout = ( - legacy_layout - if legacy_layout is not None - else _make_layout(descriptor, plans, python_names) - ) + layout = _make_layout(descriptor, plans, python_names) cls.WPIStruct = serializer_descriptor cls.__wpistruct_descriptor__ = layout From fc82399fa026d73d2271a8154ecc169cd54fbf9d Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Mon, 17 Aug 2026 04:11:07 +0000 Subject: [PATCH 03/14] fix(wpiutil): decode large generated struct arrays --- .../tests/test_datalog_reader_auto.py | 21 ++++ .../tests/test_struct_schema.py | 107 +++++++++++++----- .../wpiutil/wpistruct/_compiler.py | 37 +++++- .../wpiutil/wpistruct/_schema.py | 45 +++++--- 4 files changed, 159 insertions(+), 51 deletions(-) diff --git a/subprojects/robotpy-wpilog/tests/test_datalog_reader_auto.py b/subprojects/robotpy-wpilog/tests/test_datalog_reader_auto.py index 4fa15302c..ffe2cdb45 100644 --- a/subprojects/robotpy-wpilog/tests/test_datalog_reader_auto.py +++ b/subprojects/robotpy-wpilog/tests/test_datalog_reader_auto.py @@ -122,6 +122,27 @@ def test_iter_auto_decodes_generated_struct(tmp_path): assert dataclasses.asdict(instance) == {"i": 3, "j": 4} +def test_iter_auto_decodes_generated_struct_with_large_array(tmp_path): + path = tmp_path / "generated-struct-large-array.wpilog" + payload = bytes(index & 0xFF for index in range(65537)) + with wpilog.DataLogWriter(str(path)) as log: + schema_entry = log.start("/.schema/struct:LargeArray", "structschema", "", 1) + log.append_string(schema_entry, "uint8 values[65537]", 2) + data_entry = log.start("/value", "struct:LargeArray", "", 3) + log.append_raw(data_entry, payload, 4) + + values = _read_auto(path) + [generated] = [value for _, entry, value in values if entry.type == "structschema"] + [instance] = [ + value for _, entry, value in values if entry.type == "struct:LargeArray" + ] + + assert dataclasses.is_dataclass(generated) + assert dataclasses.fields(generated)[0].type == tuple[wpistruct.uint8, ...] + assert type(instance) is generated + assert bytes(instance.values) == payload + + def test_iter_auto_decodes_registered_struct_array(tmp_path): path = tmp_path / "registered-struct-array.wpilog" with wpilog.DataLogWriter(str(path)) as log: diff --git a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py index 0caf006f2..d07b231f5 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py @@ -131,36 +131,80 @@ def counting_search(pattern, *args, **kwargs): def test_generated_array_representability_limit(): - largest = make_wpistruct_from_schema( - "LargestGeneratedArray", "uint8 values[65536]", nested={} + generated = make_wpistruct_from_schema( + "OversizedGeneratedArray", "uint8 values[65537]", nested={} ) - assert wpistruct.get_size(largest) == 65536 - with pytest.raises( - ValueError, - match=( - r"generated wpistruct arrays contain 65537 total elements; " - r"support at most 65536" - ), - ): - make_wpistruct_from_schema( - "OversizedGeneratedArray", "uint8 values[65537]", nested={} - ) + field = dataclasses.fields(generated)[0] + assert typing.get_args(field.type) == (wpistruct.uint8, Ellipsis) + assert wpistruct.get_size(generated) == 65537 + values = tuple(index & 0xFF for index in range(65537)) + value = generated(values) + assert wpistruct.unpack(generated, wpistruct.pack(value)) == value def test_generated_array_representability_budget_is_cumulative(): - with pytest.raises( - ValueError, - match=( - r"generated wpistruct arrays contain 65538 total elements; " - r"support at most 65536" - ), - ): - make_wpistruct_from_schema( - "CumulativelyOversizedGeneratedArrays", - "uint8 first[32769]; uint8 second[32769]", - nested={}, - ) + generated = make_wpistruct_from_schema( + "CumulativelyOversizedGeneratedArrays", + "uint8 first[32769]; uint8 second[32769]", + nested={}, + ) + + first, second = dataclasses.fields(generated) + first_args = typing.get_args(first.type) + assert len(first_args) == 32769 + assert set(first_args) == {wpistruct.uint8} + assert typing.get_args(second.type) == (wpistruct.uint8, Ellipsis) + assert wpistruct.get_size(generated) == 65538 + value = generated((0,) * 32769, (1,) * 32769) + assert wpistruct.unpack(generated, wpistruct.pack(value)) == value + + +def test_generated_compact_arrays_preserve_descriptor_behavior(monkeypatch): + monkeypatch.setattr(schema_module, "_MAX_GENERATED_TUPLE_ELEMENTS", 0) + inner = make_wpistruct_from_schema("Inner", "uint8 value", nested={}) + generated = make_wpistruct_from_schema( + "CompactArrays", + "uint8 samples[2]; enum {OFF=0,AUTO=1} uint8 modes[2]; " + "Inner children[2]; uint8 singleton[1]", + nested={"Inner": inner}, + ) + + samples, modes, children, singleton = dataclasses.fields(generated) + mode_type = typing.get_args(modes.type)[0] + assert typing.get_args(samples.type) == (wpistruct.uint8, Ellipsis) + assert typing.get_args(modes.type) == (mode_type, Ellipsis) + assert typing.get_args(children.type) == (inner, Ellipsis) + assert typing.get_args(singleton.type) == (wpistruct.uint8, Ellipsis) + + value = generated( + (1, 2), + (mode_type.OFF, mode_type.AUTO), + (inner(3), inner(4)), + (5,), + ) + encoded = wpistruct.pack(value) + decoded = wpistruct.unpack(generated, encoded) + assert decoded == value + assert decoded.singleton == (5,) + assert isinstance(decoded.singleton, tuple) + + for invalid_samples in ((1,), (1, 2, 3)): + with pytest.raises(ValueError, match="error packing data"): + wpistruct.pack(dataclasses.replace(value, samples=invalid_samples)) + + for invalid_buffer in (encoded[:-1], encoded + b"\x00"): + with pytest.raises(ValueError, match="buffer must be 7 bytes"): + wpistruct.unpack(generated, invalid_buffer) + + +def test_authored_variadic_tuple_remains_rejected(): + with pytest.raises(TypeError, match="tuple fields must be fixed-length"): + + @wpistruct.make_wpistruct + @dataclasses.dataclass + class AuthoredVariadic: + values: tuple[wpistruct.uint8, ...] def test_generated_empty_schema_and_float_aliases(): @@ -368,11 +412,18 @@ def stage(self, type_name, schema): ] == [[type_name] for type_name in expected_names] -def test_failed_generated_class_construction_does_not_mutate_registry(): +def test_failed_generated_class_construction_does_not_mutate_registry(monkeypatch): registry = StructTypeRegistry(()) + sentinel = RuntimeError("sentinel class construction failure") + + def fail_make_dataclass(*args, **kwargs): + raise sentinel - with pytest.raises(ValueError, match="support at most 65536"): - registry.add_schema("Value", "uint8 samples[65537]") + with monkeypatch.context() as patch: + patch.setattr(schema_module.dataclasses, "make_dataclass", fail_make_dataclass) + with pytest.raises(RuntimeError) as exc_info: + registry.add_schema("Value", "uint8 samples[2]") + assert exc_info.value is sentinel recovered = registry.add_schema("Value", "uint8 value") assert wpistruct.unpack(recovered, b"\x07") == recovered(7) diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py index 5976c9a0f..bce6bc482 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py @@ -65,17 +65,29 @@ def _get_supported_type_names(): return f"{supported_names}, or fixed-length homogeneous tuple of a supported type" -def _get_fixed_tuple_array_info(cls_name: str, field_name: str, field_type: type): +def _get_fixed_tuple_array_info( + cls_name: str, + field_name: str, + field_type: type, + generated_array_size: int | None = None, +): origin = typing.get_origin(field_type) if origin is not tuple: return None args = typing.get_args(field_type) - if not args or args[-1] is Ellipsis: + if not args: raise TypeError( f"{cls_name}.{field_name} has unsupported tuple type hint: " "tuple fields must be fixed-length and homogeneous" ) from None + if args[-1] is Ellipsis: + if generated_array_size is None: + raise TypeError( + f"{cls_name}.{field_name} has unsupported tuple type hint: " + "tuple fields must be fixed-length and homogeneous" + ) from None + return args[0], generated_array_size element_type = args[0] if not all(arg == element_type for arg in args): @@ -128,6 +140,7 @@ def _resolve_field_plan( field_name: str, annotation: type, base_type: type, + generated_array_size: int | None = None, ) -> FieldPlan: _, metadata = _split_annotated(annotation) field_type = base_type @@ -174,7 +187,9 @@ def _resolve_field_plan( is_char=True, ) - array_info = _get_fixed_tuple_array_info(cls_name, field_name, field_type) + array_info = _get_fixed_tuple_array_info( + cls_name, field_name, field_type, generated_array_size + ) if array_info: element_type, array_size = array_info is_array = True @@ -267,7 +282,11 @@ def _resolve_field_plan( ) -def _resolve_field_plans(cls: type, cls_name: str) -> list[FieldPlan]: +def _resolve_field_plans( + cls: type, + cls_name: str, + generated_array_sizes: typing.Mapping[str, int] | None = None, +) -> list[FieldPlan]: resolved_hints = typing.get_type_hints(cls, include_extras=True) base_hints = typing.get_type_hints(cls) return [ @@ -277,6 +296,11 @@ def _resolve_field_plans(cls: type, cls_name: str) -> list[FieldPlan]: field.name, resolved_hints[field.name], base_hints[field.name], + ( + generated_array_sizes.get(field.name) + if generated_array_sizes is not None + else None + ), ) for field_idx, field in enumerate(dataclasses.fields(cls)) ] @@ -485,6 +509,7 @@ def compile_wpistruct( schema_override=None, descriptor=None, python_names=None, + generated_array_sizes: typing.Mapping[str, int] | None = None, ) -> type: cls_name = _class_name(cls) if struct_name is None: @@ -493,11 +518,11 @@ def compile_wpistruct( else: err_name = f"{struct_name} ({cls_name})" - plans = _resolve_field_plans(cls, cls_name) + plans = _resolve_field_plans(cls, cls_name, generated_array_sizes) schema = ( schema_override if schema_override is not None else _schema_for_plans(plans) ) - use_descriptor_codec = any( + use_descriptor_codec = bool(generated_array_sizes) or any( plan.is_char or plan.enum_type is not None or plan.bit_width is not None for plan in plans ) diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py index 14578aa57..fb235e05c 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py @@ -62,12 +62,10 @@ def __init__(self, type_name: str): "double": double, } -# Generated fixed arrays are represented as Python tuples and as fixed tuple -# annotations containing one type reference per element. A cumulative 65,536 -# elements caps each class's annotation pointer payload at 512 KiB on 64-bit -# CPython while leaving ample room for ordinary robotics sample arrays. Larger -# schemas remain valid WPILib grammar, but are not safely representable as -# generated Python classes. +# Fixed tuple annotations contain one type reference per array element. Limit +# that cumulative annotation expansion to 65,536 references (512 KiB of +# pointers on 64-bit CPython); arrays beyond the budget use compact variadic +# annotations while their exact extents remain in the native descriptor. _MAX_GENERATED_TUPLE_ELEMENTS = 65_536 @@ -151,6 +149,7 @@ def _field_annotation( python_name: str, nested, used_enum_names: set[str], + compact_array: bool = False, ): is_array = field.is_array @@ -173,7 +172,11 @@ def _field_annotation( return typing.Annotated[str, CharArray(field.array_size)] if is_array: - annotation = _fixed_tuple(annotation, field.array_size) + annotation = ( + tuple[annotation, ...] + if compact_array + else _fixed_tuple(annotation, field.array_size) + ) if field.is_bit_field: metadata.append(BitField(field.bit_width)) if metadata: @@ -307,22 +310,29 @@ def make_wpistruct_from_schema( python_names = [] used_enum_names: set[str] = set() generated_tuple_elements = 0 + compact_array_sizes: dict[str, int] = {} for field in descriptor.fields: - if field.type != "char" and field.is_array: - generated_tuple_elements += field.array_size - if generated_tuple_elements > _MAX_GENERATED_TUPLE_ELEMENTS: - raise ValueError( - "generated wpistruct arrays contain " - f"{generated_tuple_elements} total elements; support at most " - f"{_MAX_GENERATED_TUPLE_ELEMENTS}" - ) - field_name = field.name if field_name in _GENERATED_ATTRIBUTE_NAMES: field_name = f"{field_name}_" python_name = _unique_identifier(field_name, used_names) + + compact_array = False + if field.type != "char" and field.is_array: + expanded_elements = generated_tuple_elements + field.array_size + if expanded_elements <= _MAX_GENERATED_TUPLE_ELEMENTS: + generated_tuple_elements = expanded_elements + else: + compact_array = True + compact_array_sizes[python_name] = field.array_size + annotation = _field_annotation( - name, field, python_name, nested, used_enum_names + name, + field, + python_name, + nested, + used_enum_names, + compact_array=compact_array, ) fields.append((python_name, annotation)) python_names.append(python_name) @@ -337,6 +347,7 @@ def make_wpistruct_from_schema( schema_override=schema, descriptor=descriptor, python_names=python_names, + generated_array_sizes=compact_array_sizes or None, ) for field in dataclasses.fields(generated): annotation = field.type From 23f7e3aacdac03614b501deab79a2eb31e52b4c3 Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Mon, 17 Aug 2026 04:37:10 +0000 Subject: [PATCH 04/14] fix(wpiutil): guard zero-size descriptor arrays --- .../tests/test_struct_schema.py | 72 +++++++++++++++++++ .../wpiutil/wpistruct/_compiler.py | 33 ++++++++- 2 files changed, 104 insertions(+), 1 deletion(-) diff --git a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py index d07b231f5..d53b374f3 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py @@ -6,6 +6,7 @@ import pytest from wpiutil import wpistruct +import wpiutil.wpistruct._compiler as compiler_module import wpiutil.wpistruct._schema as schema_module from wpiutil.wpistruct._schema import ( InvalidStructSchema, @@ -198,6 +199,77 @@ def test_generated_compact_arrays_preserve_descriptor_behavior(monkeypatch): wpistruct.unpack(generated, invalid_buffer) +@pytest.mark.parametrize("operation", ["pack", "unpack"]) +def test_zero_size_nested_array_codec_materialization_limit(monkeypatch, operation): + monkeypatch.setattr(schema_module, "_MAX_GENERATED_TUPLE_ELEMENTS", 0) + monkeypatch.setattr(compiler_module, "_MAX_DESCRIPTOR_ZERO_SIZE_ARRAY_ELEMENTS", 2) + empty = make_wpistruct_from_schema("Empty", "", nested={}) + generated = make_wpistruct_from_schema( + "ZeroSizeNestedArray", "Empty values[3]", nested={"Empty": empty} + ) + + field = dataclasses.fields(generated)[0] + assert typing.get_args(field.type) == (empty, Ellipsis) + assert wpistruct.get_size(generated) == 0 + + native_calls = 0 + + def fail_native(*args, **kwargs): + nonlocal native_calls + native_calls += 1 + raise RuntimeError("native descriptor codec was called") + + monkeypatch.setattr(compiler_module, f"{operation}_schema", fail_native) + with pytest.raises(ValueError) as exc_info: + if operation == "pack": + wpistruct.pack(generated((empty(), empty(), empty()))) + else: + wpistruct.unpack(generated, b"") + + assert native_calls == 0 + error = str(exc_info.value) + assert "field values" in error + assert "3" in error + assert "zero-size nested array" in error + assert "limit is 2" in error + + +def test_compact_primitive_descriptor_arrays_avoid_redundant_tuple_copies( + monkeypatch, +): + monkeypatch.setattr(schema_module, "_MAX_GENERATED_TUPLE_ELEMENTS", 0) + generated = make_wpistruct_from_schema( + "CompactPrimitiveArray", "uint8 values[2]", nested={} + ) + original_pack_schema = compiler_module.pack_schema + original_unpack_schema = compiler_module.unpack_schema + packed_field_values = [] + unpacked_field_values = [] + + def capture_pack_values(descriptor, values): + packed_field_values.append(values[0]) + return original_pack_schema(descriptor, values) + + def capture_unpack_values(descriptor, buffer): + values = original_unpack_schema(descriptor, buffer) + unpacked_field_values.append(values[0]) + return values + + monkeypatch.setattr(compiler_module, "pack_schema", capture_pack_values) + monkeypatch.setattr(compiler_module, "unpack_schema", capture_unpack_values) + + sequence = [1, 2] + assert wpistruct.pack(generated(sequence)) == b"\x01\x02" + assert packed_field_values[-1] is sequence + + assert wpistruct.pack(generated(iter((3, 4)))) == b"\x03\x04" + assert packed_field_values[-1] == (3, 4) + + decoded = wpistruct.unpack(generated, b"\x05\x06") + assert decoded.values is unpacked_field_values[-1] + assert decoded.values == (5, 6) + + def test_authored_variadic_tuple_remains_rejected(): with pytest.raises(TypeError, match="tuple fields must be fixed-length"): diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py index bce6bc482..0de39d259 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py @@ -41,6 +41,10 @@ _sized_integer_types = (int8, uint8, int16, uint16, int32, uint32, int64, uint64) _signed_integer_types = (int8, int16, int32, int64) +# A zero-size nested array has no payload-based bound on its semantic element +# count. Prevent the descriptor codec from materializing unbounded containers. +_MAX_DESCRIPTOR_ZERO_SIZE_ARRAY_ELEMENTS = 65_536 + @dataclasses.dataclass(slots=True) class FieldPlan: @@ -404,7 +408,12 @@ def _descriptor_pack_value(plan: FieldPlan, value): if plan.is_char: return value if plan.is_array: - values = tuple(_descriptor_pack_element(plan, item) for item in value) + if plan.enum_type is not None or plan.nested_type is not None: + values = tuple(_descriptor_pack_element(plan, item) for item in value) + elif isinstance(value, collections.abc.Sequence): + values = value + else: + values = tuple(value) if len(values) != plan.array_size: raise ValueError( f"field {plan.python_name} must contain {plan.array_size} values" @@ -430,6 +439,8 @@ def _descriptor_unpack_value(plan: FieldPlan, value): return char(value or "\0") if plan.is_array: values = (value,) if plan.array_size == 1 else value + if plan.enum_type is None and plan.nested_type is None: + return values return tuple(_descriptor_unpack_element(plan, item) for item in values) return _descriptor_unpack_element(plan, value) @@ -442,6 +453,23 @@ def _make_descriptor_serializer( plans: list[FieldPlan], descriptor, ) -> StructDescriptor: + zero_size_nested_arrays = tuple( + plan + for plan in plans + if plan.is_array + and plan.nested_type is not None + and wpistruct.get_size(plan.nested_type) == 0 + ) + + def check_materialization_limit(): + for plan in zero_size_nested_arrays: + if plan.array_size > _MAX_DESCRIPTOR_ZERO_SIZE_ARRAY_ELEMENTS: + raise ValueError( + f"{err_name}: field {plan.python_name} has {plan.array_size} elements " + "in a zero-size nested array; descriptor codec materialization " + f"limit is {_MAX_DESCRIPTOR_ZERO_SIZE_ARRAY_ELEMENTS}" + ) + def pack_data(value): values = tuple( _descriptor_pack_value(plan, getattr(value, plan.python_name)) @@ -450,12 +478,14 @@ def pack_data(value): return pack_schema(descriptor, values) def pack(value): + check_materialization_limit() try: return pack_data(value) except Exception as exc: raise ValueError(f"{err_name}: error packing data") from exc def pack_into(value, buffer): + check_materialization_limit() try: encoded = pack_data(value) destination = memoryview(buffer).cast("B") @@ -468,6 +498,7 @@ def pack_into(value, buffer): raise ValueError(f"{err_name}: error packing data") from exc def unpack(buffer): + check_materialization_limit() try: values = unpack_schema(descriptor, buffer) converted = ( From dd0317088830660ebdd3284e3a1292fa5598f55f Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Mon, 17 Aug 2026 04:58:01 +0000 Subject: [PATCH 05/14] fix(wpiutil): batch nested schema dependencies --- .../semiwrap/WPyStructSchema.yml | 2 + .../tests/test_schema_bridge.py | 97 +++++++++++++ .../tests/test_struct_schema.py | 69 ++++++++++ .../src/wpistruct/wpystruct_schema.cpp | 98 ++++++++++++-- .../wpiutil/src/wpistruct/wpystruct_schema.h | 2 + .../wpiutil/wpistruct/_schema.py | 127 ++++++------------ 6 files changed, 300 insertions(+), 95 deletions(-) diff --git a/subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml b/subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml index 0ede44b52..436a67386 100644 --- a/subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml +++ b/subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml @@ -55,6 +55,8 @@ classes: SchemaDatabase: Add: no_release_gil: true + AddAll: + no_release_gil: true Stage: no_release_gil: true Find: diff --git a/subprojects/robotpy-wpiutil/tests/test_schema_bridge.py b/subprojects/robotpy-wpiutil/tests/test_schema_bridge.py index b5d9cedb0..57718fb8a 100644 --- a/subprojects/robotpy-wpiutil/tests/test_schema_bridge.py +++ b/subprojects/robotpy-wpiutil/tests/test_schema_bridge.py @@ -100,6 +100,103 @@ def test_schema_descriptor_preserves_declaration_shape_metadata(): assert empty_mode.is_enum +def test_schema_database_add_all_completes_retained_dependency_chain(): + database = SchemaDatabase() + candidate = database.add("Outer", "Middle value") + + assert not candidate.is_valid + + database.add_all( + [ + ("Inner", "uint8 value"), + ("Middle", "Inner value"), + ] + ) + + assert candidate.is_valid + assert candidate.size == 1 + assert candidate.fields[0].struct_name == "Middle" + + +def test_schema_database_add_all_preserves_explicit_declaration_shapes(): + database = SchemaDatabase() + + database.add_all([("Samples", "uint8 samples[1]")]) + + descriptor = database.find("Samples") + assert descriptor is not None + assert descriptor.schema == "uint8 samples[1]" + assert descriptor.fields[0].is_array is True + assert descriptor.fields[0].array_size == 1 + + +def test_schema_database_add_all_rolls_back_malformed_batch(): + database = SchemaDatabase() + retained = database.add("Outer", "Inner value") + existing = database.add("Existing", "uint8 value") + + with pytest.raises(ValueError, match="expected identifier"): + database.add_all( + [ + ("Inner", "uint16 value"), + ("Malformed", "int32 [2]"), + ] + ) + + assert not retained.is_valid + assert database.find("Inner").schema == "" + assert database.find("Malformed") is None + assert database.find("Existing").schema == existing.schema + assert database.find("Existing").size == existing.size + + database.add_all([("Inner", "uint16 value")]) + assert retained.is_valid + assert retained.size == 2 + + +def test_schema_database_add_all_rolls_back_conflicting_batch(): + database = SchemaDatabase() + retained = database.add("Outer", "Parent value") + existing = database.add("Existing", "uint8 value") + + with pytest.raises(ValueError, match="conflicting schema for Existing"): + database.add_all( + [ + ("Inner", "uint16 value"), + ("Existing", "uint32 value"), + ("Parent", "Inner value"), + ] + ) + + assert not retained.is_valid + assert database.find("Inner") is None + assert database.find("Parent").schema == "" + assert database.find("Existing").schema == existing.schema + assert database.find("Existing").size == existing.size + + database.add_all( + [ + ("Inner", "uint16 value"), + ("Parent", "Inner value"), + ] + ) + assert retained.is_valid + assert retained.size == 2 + + +def test_schema_database_add_all_candidate_outlives_database(): + database = SchemaDatabase() + candidate = database.add("Outer", "Inner value") + database.add_all([("Inner", "uint8 value")]) + + del database + gc.collect() + + assert candidate.is_valid + assert candidate.size == 1 + assert candidate.fields[0].struct_name == "Inner" + + def test_schema_database_stages_without_mutating_source(): source = SchemaDatabase() source.add("First", "uint8 value") diff --git a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py index d53b374f3..669f2ab39 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py @@ -448,6 +448,7 @@ def test_registry_independent_schemas_use_one_native_add_each(monkeypatch): class CountingSchemaDatabase: instances = [] add_calls = [] + add_all_calls = [] stage_calls = [] def __init__(self, wrapped=None): @@ -460,6 +461,11 @@ def add(self, type_name, schema): type(self).add_calls.append(type_name) return self._wrapped.add(type_name, schema) + def add_all(self, definitions): + definitions = tuple(definitions) + type(self).add_all_calls.append(definitions) + return self._wrapped.add_all(definitions) + def find(self, type_name): return self._wrapped.find(type_name) @@ -476,6 +482,7 @@ def stage(self, type_name, schema): registry.add_schema(type_name, "uint8 value") assert CountingSchemaDatabase.stage_calls == [] + assert CountingSchemaDatabase.add_all_calls == [] assert CountingSchemaDatabase.add_calls == expected_names assert [ database.instance_adds @@ -484,6 +491,53 @@ def stage(self, type_name, schema): ] == [[type_name] for type_name in expected_names] +def test_registry_dependency_chain_uses_one_linear_batch_per_parent(monkeypatch): + native_database = schema_module.SchemaDatabase + + class CountingSchemaDatabase: + add_calls = [] + add_all_calls = [] + + def __init__(self): + self._wrapped = native_database() + + def add(self, type_name, schema): + type(self).add_calls.append(type_name) + return self._wrapped.add(type_name, schema) + + def add_all(self, definitions): + definitions = tuple(definitions) + type(self).add_all_calls.append(definitions) + return self._wrapped.add_all(definitions) + + def find(self, type_name): + return self._wrapped.find(type_name) + + def stage(self, type_name, schema): + return self._wrapped.stage(type_name, schema) + + monkeypatch.setattr(schema_module, "SchemaDatabase", CountingSchemaDatabase) + registry = StructTypeRegistry(()) + chain_types = [registry.add_schema("Chain0", "uint8 value")] + for index in range(1, 32): + chain_types.append( + registry.add_schema(f"Chain{index}", f"Chain{index - 1} value") + ) + + assert CountingSchemaDatabase.add_calls == [f"Chain{index}" for index in range(32)] + assert len(CountingSchemaDatabase.add_all_calls) == 31 + for index, definitions in enumerate(CountingSchemaDatabase.add_all_calls, start=1): + names = [type_name for type_name, _ in definitions] + assert len(definitions) == index + assert names == [f"Chain{dependency}" for dependency in range(index)] + assert len(names) == len(set(names)) + + value = chain_types[0](7) + for chain_type in chain_types[1:]: + value = chain_type(value) + assert wpistruct.unpack(chain_types[-1], wpistruct.pack(value)) == value + + def test_failed_generated_class_construction_does_not_mutate_registry(monkeypatch): registry = StructTypeRegistry(()) sentinel = RuntimeError("sentinel class construction failure") @@ -524,6 +578,21 @@ def test_failed_unresolved_registry_schema_can_retry_after_nested_registration() assert wpistruct.unpack(outer, wpistruct.pack(value)) == value +def test_mixed_available_and_unresolved_registry_schema_preserves_retry_taxonomy(): + registry = StructTypeRegistry(()) + known = registry.add_schema("Known", "uint8 value") + + with pytest.raises( + schema_module._UnresolvedStructSchema, match="Missing.*not registered" + ): + registry.add_schema("Outer", "Known known; Missing missing") + + missing = registry.add_schema("Missing", "uint16 value") + outer = registry.add_schema("Outer", "Known known; Missing missing") + value = outer(known(7), missing(0x1234)) + assert wpistruct.unpack(outer, wpistruct.pack(value)) == value + + def test_registry_duplicate_and_conflict_behavior(): registry = StructTypeRegistry(()) first = registry.add_schema("Value", "int32 value;") diff --git a/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.cpp b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.cpp index 03ab496fb..670f2f13b 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.cpp +++ b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.cpp @@ -132,6 +132,12 @@ std::vector ParseDeclarationShapes(std::string_view schema) { } } +struct PreparedDefinition { + std::string name; + std::string schema; + std::vector shapes; +}; + bool SchemasEqual(std::string_view lhs, std::string_view rhs) { auto parsedLhs = ParseSchema(lhs); auto parsedRhs = ParseSchema(rhs); @@ -178,6 +184,17 @@ void ValidateArrayExtentsForPlatform(std::string_view descriptorName, } } +PreparedDefinition PrepareDefinition(std::string_view name, + std::string_view schema) { + auto parsed = ParseSchema(schema); + auto shapes = ParseDeclarationShapes(schema); + if (shapes.size() != parsed.declarations.size()) { + throw pybind11::value_error("failed to analyze schema declarations"); + } + ValidateArrayExtentsForPlatform(name, schema); + return {std::string{name}, std::string{schema}, std::move(shapes)}; +} + void ValidateDescriptorLayout(const wpi::util::StructDescriptor& descriptor) { if (!descriptor.IsValid()) { return; @@ -223,15 +240,26 @@ void ValidateDatabaseLayouts( ValidateDescriptorLayout(*candidate); } +void ValidateCompleteDatabaseLayouts( + const wpi::util::StructDescriptorDatabase& database, + const std::map>& definitions) { + for (const auto& definition : definitions) { + const auto* descriptor = database.Find(definition.first); + if (!descriptor) { + throw pybind11::value_error("failed to reconstruct schema database"); + } + if (!descriptor->IsValid()) { + throw pybind11::value_error("unresolved schema definition for " + + definition.first); + } + ValidateDescriptorLayout(*descriptor); + } +} + std::shared_ptr BuildStagedDatabase( const std::shared_ptr& source, std::string_view name, std::string_view schema) { - auto parsed = ParseSchema(schema); - auto shapes = ParseDeclarationShapes(schema); - if (shapes.size() != parsed.declarations.size()) { - throw pybind11::value_error("failed to analyze schema declarations"); - } - ValidateArrayExtentsForPlatform(name, schema); + auto prepared = PrepareDefinition(name, schema); bool duplicate = false; if (auto existing = source->definitions.find(name); @@ -254,8 +282,8 @@ std::shared_ptr BuildStagedDatabase( } } if (duplicate) { - staged->definitions[std::string{name}] = std::string{schema}; - staged->shapes[std::string{name}] = std::move(shapes); + staged->definitions[prepared.name] = prepared.schema; + staged->shapes[prepared.name] = std::move(prepared.shapes); return staged; } @@ -266,8 +294,8 @@ std::shared_ptr BuildStagedDatabase( std::string descriptorName = descriptor->GetName(); ValidateDatabaseLayouts(*staged->database, source->definitions, descriptorName); - staged->definitions.emplace(descriptorName, schema); - staged->shapes.emplace(std::move(descriptorName), std::move(shapes)); + staged->definitions.emplace(descriptorName, std::move(prepared.schema)); + staged->shapes.emplace(std::move(descriptorName), std::move(prepared.shapes)); return staged; } @@ -654,6 +682,56 @@ SchemaDescriptor SchemaDatabase::Add(std::string_view name, return SchemaDescriptor{m_impl, std::string{name}}; } +void SchemaDatabase::AddAll( + const std::vector>& definitions) { + if (definitions.empty()) { + return; + } + + std::vector prepared; + prepared.reserve(definitions.size()); + for (const auto& [name, schema] : definitions) { + prepared.emplace_back(PrepareDefinition(name, schema)); + } + + auto staged = std::make_shared(); + staged->definitions = m_impl->definitions; + staged->shapes = m_impl->shapes; + std::string error; + for (const auto& [name, schema] : m_impl->definitions) { + if (!staged->database->Add(name, schema, &error)) { + throw pybind11::value_error("failed to reconstruct schema database: " + + error); + } + } + + for (auto& definition : prepared) { + if (auto existing = staged->definitions.find(definition.name); + existing != staged->definitions.end()) { + if (!SchemasEqual(existing->second, definition.schema)) { + throw pybind11::value_error("conflicting schema for " + + definition.name); + } + continue; + } + + const auto* descriptor = + staged->database->Add(definition.name, definition.schema, &error); + if (!descriptor) { + throw pybind11::value_error(error); + } + std::string descriptorName = descriptor->GetName(); + staged->definitions.emplace(descriptorName, std::move(definition.schema)); + staged->shapes.emplace(std::move(descriptorName), + std::move(definition.shapes)); + } + + ValidateCompleteDatabaseLayouts(*staged->database, staged->definitions); + m_impl->database = std::move(staged->database); + m_impl->definitions = std::move(staged->definitions); + m_impl->shapes = std::move(staged->shapes); +} + SchemaDatabase SchemaDatabase::Stage(std::string_view name, std::string_view schema) const { SchemaDatabase staged; diff --git a/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.h b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.h index 1585d9011..1bbbe9d2d 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.h +++ b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_schema.h @@ -56,6 +56,8 @@ class SchemaDatabase { public: SchemaDatabase(); SchemaDescriptor Add(std::string_view name, std::string_view schema); + void AddAll( + const std::vector>& definitions); SchemaDatabase Stage(std::string_view name, std::string_view schema) const; std::optional Find(std::string_view name) const; diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py index fb235e05c..cbd07abeb 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py @@ -184,9 +184,9 @@ def _field_annotation( return annotation -def _schema_operation(operation, type_name: str, schema: str): +def _schema_operation(operation, *args): try: - return operation(type_name, schema) + return operation(*args) except UnicodeDecodeError as exc: raise InvalidStructSchema(f"parse error: {exc}") from exc except ValueError as exc: @@ -199,26 +199,12 @@ def _add_schema(database: SchemaDatabase, type_name: str, schema: str): return _schema_operation(database.add, type_name, schema) -def _stage_schema(database: SchemaDatabase, type_name: str, schema: str): - return _schema_operation(database.stage, type_name, schema) +def _add_schemas(database: SchemaDatabase, definitions): + return _schema_operation(database.add_all, definitions) -def _native_seed_schema(struct_type: type) -> str: - layout = struct_type.__wpistruct_descriptor__ - declarations = [] - for index, field in enumerate(layout.fields): - if field.enum_values: - values = ",".join(f"{name}={value}" for name, value in field.enum_values) - type_name = f"enum {{{values}}} {field.type_name}" - else: - type_name = field.type_name - array_suffix = f"[{field.array_size}]" if field.array_size > 1 else "" - is_bitfield = field.nested_type is None and ( - field.bit_shift != 0 or field.bit_width != field.size * 8 - ) - bitfield_suffix = f":{field.bit_width}" if is_bitfield else "" - declarations.append(f"{type_name} field{index}{array_suffix}{bitfield_suffix}") - return "; ".join(declarations) +def _stage_schema(database: SchemaDatabase, type_name: str, schema: str): + return _schema_operation(database.stage, type_name, schema) def _add_nested_dependency_schemas( @@ -226,41 +212,38 @@ def _add_nested_dependency_schemas( descriptor, nested: typing.Mapping[str, type], ) -> None: - definitions = {} + definitions = [] + seen_definitions = set() - def add_nested(type_string: str, schema: str): - type_name = type_string.removeprefix("struct:") - previous = definitions.get(type_name) - if previous == schema: - return + def collect_nested(type_string: str, schema: str): + definition = (type_string.removeprefix("struct:"), schema) + if definition not in seen_definitions: + seen_definitions.add(definition) + definitions.append(definition) - try: - database.add(type_name, schema) - effective_schema = schema - except UnicodeDecodeError: - struct_type = nested.get(type_name) - if struct_type is None or not hasattr( - struct_type, "__wpistruct_descriptor__" - ): - raise - effective_schema = _native_seed_schema(struct_type) - try: - database.add(type_name, effective_schema) - except UnicodeDecodeError: - # A Unicode type name cannot be referenced by raw native schema - # grammar. The unresolved candidate reports the type name below. - return - definitions[type_name] = effective_schema - - required_names = { + required_names = dict.fromkeys( field.struct_name for field in descriptor.fields if field.struct_name is not None - } + ) + missing = None for type_name in required_names: nested_type = nested.get(type_name) - if nested_type is not None: - wpistruct.for_each_nested(nested_type, add_nested) + if nested_type is None: + if missing is None: + missing = type_name + else: + wpistruct.for_each_nested(nested_type, collect_nested) + + if definitions: + try: + _add_schemas(database, definitions) + except ValueError as exc: + if missing is not None and str(exc).startswith( + "unresolved schema definition for " + ): + raise _UnresolvedStructSchema(missing) from exc + raise def _make_candidate_descriptor( @@ -371,47 +354,21 @@ def __init__(self, struct_types: typing.Iterable[type]): self._types[type_name] = struct_type self._supplied_names.add(type_name) - seed_types: dict[str, type] = {} + seed_definitions = [] + seen_seed_definitions = set() - def collect_seed_types(struct_type: type) -> None: - type_name = wpistruct.get_type_name(struct_type) - if type_name in seed_types: - return - seed_types[type_name] = struct_type - layout = getattr(struct_type, "__wpistruct_descriptor__", None) - if layout is not None: - for field in layout.fields: - if field.nested_type is not None: - collect_seed_types(field.nested_type) + def collect_nested(type_string: str, schema: str): + definition = (type_string.removeprefix("struct:"), schema) + if definition not in seen_seed_definitions: + seen_seed_definitions.add(definition) + seed_definitions.append(definition) for struct_type in supplied_types: - collect_seed_types(struct_type) - - seed_database = SchemaDatabase() - - def add_nested(type_string: str, schema: str): - type_name = type_string.removeprefix("struct:") - try: - seed_database.add(type_name, schema) - effective_schema = schema - except UnicodeDecodeError: - struct_type = seed_types.get(type_name) - if struct_type is None or not hasattr( - struct_type, "__wpistruct_descriptor__" - ): - raise - effective_schema = _native_seed_schema(struct_type) - try: - seed_database.add(type_name, effective_schema) - except UnicodeDecodeError: - # A Unicode type name cannot be referenced by raw native - # schema grammar. Supplied-type lookup still preserves the - # authored type's exact public schema and serialization. - return - self._definitions.setdefault(type_name, effective_schema) + wpistruct.for_each_nested(struct_type, collect_nested) - for struct_type in supplied_types: - wpistruct.for_each_nested(struct_type, add_nested) + if seed_definitions: + _add_schemas(SchemaDatabase(), seed_definitions) + self._definitions.update(seed_definitions) def get(self, type_name: str) -> type | None: return self._types.get(type_name) From 5df47a0fd8ea6e8881d627b78534ced792793d3d Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Mon, 17 Aug 2026 05:05:14 +0000 Subject: [PATCH 06/14] test(wpilog): isolate copied record ownership --- .../robotpy-wpilog/tests/test_wpilog.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/subprojects/robotpy-wpilog/tests/test_wpilog.py b/subprojects/robotpy-wpilog/tests/test_wpilog.py index 75ea811a9..a6d5969e8 100644 --- a/subprojects/robotpy-wpilog/tests/test_wpilog.py +++ b/subprojects/robotpy-wpilog/tests/test_wpilog.py @@ -122,6 +122,35 @@ def read_temporary(): ) +def test_copied_data_record_keeps_temporary_reader_alive(tmp_path: Path): + path = tmp_path / "copied-data-record.wpilog" + with wpilog.DataLogWriter(str(path)) as log: + entry = log.start("/record-only", "raw", "", 11) + log.append_raw(entry, b"record-only-payload", 12) + + def read_temporary(): + reader = wpilog.DataLogReader(str(path)) + reader_ref = weakref.ref(reader) + records = iter(reader._iter_stable()) + iterator_ref = weakref.ref(records) + start_record = next(records) + start_record_ref = weakref.ref(start_record) + data_record = next(records) + with pytest.raises(StopIteration): + next(records) + return data_record, reader_ref, iterator_ref, start_record_ref + + data_record, reader_ref, iterator_ref, start_record_ref = read_temporary() + _collect_and_churn_allocator() + + assert start_record_ref() is None + assert iterator_ref() is not None + assert reader_ref() is not None + assert data_record.get_entry() == entry + assert data_record.get_timestamp() == 12 + assert data_record.get_raw() == b"record-only-payload" + + def test_metadata_record_data_keeps_source_record_alive(tmp_path: Path): path = tmp_path / "stable-metadata-record.wpilog" with wpilog.DataLogWriter(str(path)) as log: From 8b2c1d8138d5805cb29fc0685a2c78958c7b1edf Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Mon, 17 Aug 2026 14:37:36 +0000 Subject: [PATCH 07/14] fix(wpiutil): validate struct buffer bounds --- .../robotpy-wpiutil/tests/test_struct.py | 164 ++++++++++++++++++ .../wpiutil/src/wpistruct/wpystruct_fns.cpp | 25 ++- 2 files changed, 184 insertions(+), 5 deletions(-) diff --git a/subprojects/robotpy-wpiutil/tests/test_struct.py b/subprojects/robotpy-wpiutil/tests/test_struct.py index 9421f7262..01f89b758 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct.py @@ -1,12 +1,77 @@ import array +import ctypes import dataclasses import re +import sys import pytest from wpiutil import wpistruct +from wpiutil.wpistruct._schema import make_wpistruct_from_schema from wpiutil_test import module + +class _PackReachedError(RuntimeError): + pass + + +def _make_pack_probe_type(size): + class PackProbe: + def __init__(self, fail_on_call): + self.fail_on_call = fail_on_call + self.pack_calls = 0 + + def pack(value): + value.pack_calls += 1 + if value.pack_calls == value.fail_on_call: + raise _PackReachedError("pack callback reached") + return b"x" * size + + PackProbe.WPIStruct = wpistruct.StructDescriptor( + typename=f"PackProbe{size}", + schema=f"uint8 data[{size}]", + size=size, + pack=pack, + pack_into=lambda value, destination: None, + unpack=lambda buffer: None, + for_each_nested=None, + ) + return PackProbe + + +_PackProbe2 = _make_pack_probe_type(2) +_PackProbe3 = _make_pack_probe_type(3) + + +class _ConstantLengthSequence: + def __init__(self, length, item): + self.length = length + self.item = item + + def __len__(self): + return self.length + + def __getitem__(self, index): + if index != 0: + raise IndexError + return self.item + + +class _GrowingLengthSequence: + def __init__(self, item): + self.item = item + self.length_calls = 0 + + def __len__(self): + self.length_calls += 1 + return self.length_calls + + def __getitem__(self, index): + if index >= 2: + raise IndexError + return self.item + + # # Static serialization # @@ -51,6 +116,36 @@ def test_pack_array(): assert wpistruct.pack_array([module.ThingA(1), module.ThingA(2)]) == b"\x01\x02" +@pytest.mark.parametrize( + ("probe_type", "length"), + [ + ( + _PackProbe3, + ((1 << (ctypes.sizeof(ctypes.c_size_t) * 8)) - 1) // 3 + 1, + ), + (_PackProbe2, sys.maxsize // 2 + 1), + ], + ids=["size_t", "py_ssize_t"], +) +def test_pack_array_rejects_unrepresentable_total_before_packing(probe_type, length): + item = probe_type(fail_on_call=1) + values = _ConstantLengthSequence(length, item) + + with pytest.raises(OverflowError, match="packed array is too large"): + wpistruct.pack_array(values) + + assert item.pack_calls == 0 + + +def test_pack_array_uses_captured_length_for_packing_loop(): + item = _PackProbe3(fail_on_call=2) + values = _GrowingLengthSequence(item) + + assert wpistruct.pack_array(values) == b"xxx" + assert values.length_calls == 1 + assert item.pack_calls == 1 + + def test_pack_into(): buf = bytearray(1) wpistruct.pack_into(module.ThingA(1), buf) @@ -108,6 +203,15 @@ def test_unpack_array(): ] +@pytest.mark.parametrize("buffer_type", [bytes, bytearray, memoryview]) +def test_unpack_operations_accept_contiguous_byte_buffers(buffer_type): + assert wpistruct.unpack(module.ThingA, buffer_type(b"\x07")) == module.ThingA(7) + assert wpistruct.unpack_array(module.ThingA, buffer_type(b"\x07\x08")) == [ + module.ThingA(7), + module.ThingA(8), + ] + + # def test_unpack_into(): # r1 = module.ThingA(1) # r2 = module.ThingA(2) @@ -214,6 +318,61 @@ def test_user_unpack(): assert wpistruct.unpack(MyStruct, b"\x02\x00\x00\x00\x01\x00\x00\x60\x40") == v +_GeneratedBufferStruct = make_wpistruct_from_schema( + "GeneratedBufferStruct", "uint16 value", nested={} +) + + +def _make_strided_buffer(encoded, stride): + backing = bytearray(len(encoded) * 2) + if stride == 2: + buffer = memoryview(backing)[::2] + else: + buffer = memoryview(backing)[len(encoded) - 1 :: -1] + buffer[:] = encoded + return buffer + + +@pytest.mark.parametrize( + ("struct_type", "scalar_bytes", "array_bytes"), + [ + ( + module.Outer, + b"\x01\x02\x00\x00\x00", + b"\x01\x02\x00\x00\x00\x03\x04\x00\x00\x00", + ), + ( + MyStruct, + b"\x02\x00\x00\x00\x01\x00\x00\x60\x40", + b"\x02\x00\x00\x00\x01\x00\x00\x60\x40" + b"\x03\x00\x00\x00\x00\x00\x00\x80\x3f", + ), + (_GeneratedBufferStruct, b"\x34\x12", b"\x34\x12\x78\x56"), + ], + ids=["native", "authored", "generated"], +) +@pytest.mark.parametrize( + ("operation", "encoded_attribute"), + [(wpistruct.unpack, "scalar_bytes"), (wpistruct.unpack_array, "array_bytes")], + ids=["unpack", "unpack_array"], +) +@pytest.mark.parametrize("stride", [2, -1]) +def test_unpack_operations_reject_noncontiguous_buffers( + struct_type, + scalar_bytes, + array_bytes, + operation, + encoded_attribute, + stride, +): + encoded = scalar_bytes if encoded_attribute == "scalar_bytes" else array_bytes + buffer = _make_strided_buffer(encoded, stride) + assert bytes(buffer) == encoded + + with pytest.raises(ValueError, match="buffer must be contiguous"): + operation(struct_type, buffer) + + @wpistruct.make_wpistruct @dataclasses.dataclass class Empty: @@ -232,6 +391,11 @@ def test_user_empty_struct_array_unpack_is_rejected(): wpistruct.unpack_array(Empty, b"") +def test_pack_array_preserves_empty_and_zero_size_structs(): + assert wpistruct.pack_array([]) == b"" + assert wpistruct.pack_array([Empty(), Empty()]) == b"" + + @wpistruct.make_wpistruct(name="SingleFieldStruct") @dataclasses.dataclass class SingleFieldStruct: diff --git a/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_fns.cpp b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_fns.cpp index 408bb4ddb..aec4b96a7 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_fns.cpp +++ b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_fns.cpp @@ -1,6 +1,8 @@ #include "wpystruct_fns.h" +#include + #include "wpystruct.h" void forEachNested( @@ -55,7 +57,16 @@ py::bytes packArray(const py::sequence& seq) { WPyStructInfo info(py::type::of(seq[0])); auto sz = wpi::util::GetStructSize(info); + if (sz != 0 && len > std::numeric_limits::max() / sz) { + PyErr_SetString(PyExc_OverflowError, "packed array is too large"); + throw py::error_already_set(); + } + auto total = sz * len; + if (total > static_cast(PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "packed array is too large"); + throw py::error_already_set(); + } PyObject* b = PyBytes_FromStringAndSize(NULL, total); if (b == NULL) { @@ -70,12 +81,12 @@ py::bytes packArray(const py::sequence& seq) { } auto bytes_obj = py::reinterpret_steal(b); + auto output = + std::span(reinterpret_cast(pybuf), static_cast(pysz)); - for (const auto& v : seq) { - WPyStruct wv(v); - auto s = std::span(reinterpret_cast(pybuf), sz); - wpi::util::PackStruct(s, wv, info); - pybuf += sz; + for (size_t i = 0; i < len; ++i) { + WPyStruct wv(seq[i]); + wpi::util::PackStruct(output.subspan(i * sz, sz), wv, info); } return bytes_obj; @@ -111,6 +122,8 @@ WPyStruct unpack(const py::type& t, const py::buffer& b) { throw py::value_error("buffer must only contain bytes"); } else if (req.ndim != 1) { throw py::value_error("buffer must only have a single dimension"); + } else if (req.strides[0] != 1) { + throw py::value_error("buffer must be contiguous"); } if (req.size != sz) { @@ -131,6 +144,8 @@ py::typing::List unpackArray(const py::type& t, throw py::value_error("buffer must only contain bytes"); } else if (req.ndim != 1) { throw py::value_error("buffer must only have a single dimension"); + } else if (req.strides[0] != 1) { + throw py::value_error("buffer must be contiguous"); } if (sz == 0) { From 4bb1b2cf78083868cf357155be8e003940f18291 Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Mon, 17 Aug 2026 14:51:27 +0000 Subject: [PATCH 08/14] fix(wpiutil): address final struct buffer review --- subprojects/robotpy-wpiutil/tests/test_struct.py | 7 ++++++- .../wpiutil/src/wpistruct/wpystruct_fns.cpp | 3 ++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/subprojects/robotpy-wpiutil/tests/test_struct.py b/subprojects/robotpy-wpiutil/tests/test_struct.py index 01f89b758..08655ea68 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct.py @@ -39,6 +39,7 @@ def pack(value): return PackProbe +_PackProbe0 = _make_pack_probe_type(0) _PackProbe2 = _make_pack_probe_type(2) _PackProbe3 = _make_pack_probe_type(3) @@ -121,7 +122,7 @@ def test_pack_array(): [ ( _PackProbe3, - ((1 << (ctypes.sizeof(ctypes.c_size_t) * 8)) - 1) // 3 + 1, + ((1 << (ctypes.sizeof(ctypes.c_size_t) * 8)) - 1) // 3 + 2, ), (_PackProbe2, sys.maxsize // 2 + 1), ], @@ -395,6 +396,10 @@ def test_pack_array_preserves_empty_and_zero_size_structs(): assert wpistruct.pack_array([]) == b"" assert wpistruct.pack_array([Empty(), Empty()]) == b"" + item = _PackProbe0(fail_on_call=3) + assert wpistruct.pack_array([item, item]) == b"" + assert item.pack_calls == 2 + @wpistruct.make_wpistruct(name="SingleFieldStruct") @dataclasses.dataclass diff --git a/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_fns.cpp b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_fns.cpp index aec4b96a7..e0bec53dc 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_fns.cpp +++ b/subprojects/robotpy-wpiutil/wpiutil/src/wpistruct/wpystruct_fns.cpp @@ -68,7 +68,8 @@ py::bytes packArray(const py::sequence& seq) { throw py::error_already_set(); } - PyObject* b = PyBytes_FromStringAndSize(NULL, total); + PyObject* b = + PyBytes_FromStringAndSize(NULL, static_cast(total)); if (b == NULL) { throw py::error_already_set(); } From 181a3287bdd370e685f2e2729647fe76c25884d8 Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Mon, 17 Aug 2026 15:07:34 +0000 Subject: [PATCH 09/14] fix(wpiutil): validate chars and batch authored schemas --- .../tests/test_struct_annotations.py | 114 ++++++++++++++++++ .../tests/test_struct_schema.py | 58 +++++++++ .../wpiutil/wpistruct/_compiler.py | 26 ++-- 3 files changed, 188 insertions(+), 10 deletions(-) diff --git a/subprojects/robotpy-wpiutil/tests/test_struct_annotations.py b/subprojects/robotpy-wpiutil/tests/test_struct_annotations.py index 4428f7044..f78900a56 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct_annotations.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct_annotations.py @@ -5,6 +5,7 @@ import pytest from wpiutil import wpistruct +import wpiutil.wpistruct._compiler as compiler_module def test_char_marker(): @@ -38,6 +39,19 @@ def test_authored_schema_and_bytes_remain_exact(): ) == AuthoredStruct(1, (2, 3)) +def test_ordinary_authored_struct_keeps_fast_codec(monkeypatch): + def fail_native_codec(*args, **kwargs): + raise AssertionError("native descriptor codec was called") + + monkeypatch.setattr(compiler_module, "pack_schema", fail_native_codec) + monkeypatch.setattr(compiler_module, "unpack_schema", fail_native_codec) + value = AuthoredStruct(1, (2, 3)) + encoded = b"\x01\0\0\0\x02\0\x03\0" + + assert wpistruct.pack(value) == encoded + assert wpistruct.unpack(AuthoredStruct, encoded) == value + + def test_authored_singleton_tuple_remains_an_array(): @wpistruct.make_wpistruct @dataclasses.dataclass @@ -232,6 +246,49 @@ def test_char_and_enum_schema_round_trip(): assert wpistruct.unpack(Packet, wpistruct.pack(value)) == value +@wpistruct.make_wpistruct +@dataclasses.dataclass +class AuthoredScalarChar: + value: wpistruct.char + + +@pytest.mark.parametrize(("value", "encoded"), [("A", b"A"), ("\0", b"\0")]) +def test_authored_scalar_char_exact_bytes_and_round_trip(value, encoded): + packed = wpistruct.pack(AuthoredScalarChar(value)) + unpacked = wpistruct.unpack(AuthoredScalarChar, encoded) + + assert packed == encoded + assert unpacked == AuthoredScalarChar(value) + assert type(unpacked.value) is wpistruct.char + + +@pytest.mark.parametrize( + ("value", "cause_type"), + [ + ("", ValueError), + ("é", ValueError), + ("变量", ValueError), + (7, TypeError), + (None, TypeError), + ], +) +def test_authored_scalar_char_rejects_invalid_values_atomically(value, cause_type): + destination = bytearray(b"\xa5") + + with pytest.raises( + ValueError, match="AuthoredScalarChar: error packing data" + ) as exc: + wpistruct.pack(AuthoredScalarChar(value)) + assert isinstance(exc.value.__cause__, cause_type) + + with pytest.raises( + ValueError, match="AuthoredScalarChar: error packing data" + ) as exc: + AuthoredScalarChar.WPIStruct.pack_into(AuthoredScalarChar(value), destination) + assert isinstance(exc.value.__cause__, cause_type) + assert destination == b"\xa5" + + def test_unknown_enum_value_is_typed_without_mutating_enum(): before_members = dict(Mode.__members__) before_values = dict(Mode._value2member_map_) @@ -644,3 +701,60 @@ def test_descriptor_codec_preserves_unpack_error_wrapper(): Packet.WPIStruct.unpack(b"\0") assert "buffer must be 7 bytes" in str(exc.value.__cause__) + + +def test_authored_dependency_chain_uses_one_batch_per_nested_candidate(monkeypatch): + native_database = compiler_module.SchemaDatabase + + class CountingSchemaDatabase: + add_calls = [] + add_all_calls = [] + operations = [] + + def __init__(self): + self._wrapped = native_database() + + def add(self, type_name, schema): + type(self).add_calls.append(type_name) + type(self).operations.append(("add", type_name)) + return self._wrapped.add(type_name, schema) + + def add_all(self, definitions): + definitions = tuple(definitions) + type(self).add_all_calls.append(definitions) + type(self).operations.append( + ("add_all", tuple(type_name for type_name, _ in definitions)) + ) + return self._wrapped.add_all(definitions) + + monkeypatch.setattr(compiler_module, "SchemaDatabase", CountingSchemaDatabase) + chain_types = [] + for index in range(32): + annotation = wpistruct.uint8 if index == 0 else chain_types[-1] + chain_type = dataclasses.make_dataclass( + f"AuthoredChain{index}", [("value", annotation)] + ) + chain_types.append( + wpistruct.make_wpistruct(name=f"AuthoredChain{index}")(chain_type) + ) + + expected_names = [f"AuthoredChain{index}" for index in range(32)] + assert CountingSchemaDatabase.add_calls == expected_names + assert len(CountingSchemaDatabase.add_all_calls) == 31 + + expected_operations = [("add", "AuthoredChain0")] + for index, definitions in enumerate(CountingSchemaDatabase.add_all_calls, start=1): + names = tuple(type_name for type_name, _ in definitions) + expected_dependencies = tuple(expected_names[:index]) + assert len(definitions) == index + assert names == expected_dependencies + assert len(definitions) == len(set(definitions)) + expected_operations.extend( + [("add", f"AuthoredChain{index}"), ("add_all", names)] + ) + assert CountingSchemaDatabase.operations == expected_operations + + value = chain_types[0](7) + for chain_type in chain_types[1:]: + value = chain_type(value) + assert wpistruct.unpack(chain_types[-1], wpistruct.pack(value)) == value diff --git a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py index 669f2ab39..c9a7b5c34 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py @@ -35,6 +35,64 @@ def test_generate_struct_from_schema(): assert wpistruct.pack(value) == b"\x02\0\0\0abc\0\x01" +@pytest.mark.parametrize(("value", "encoded"), [("A", b"A"), ("\0", b"\0")]) +def test_generated_scalar_char_exact_bytes_and_round_trip(value, encoded): + generated = make_wpistruct_from_schema( + "GeneratedScalarChar", "char value", nested={} + ) + + unpacked = wpistruct.unpack(generated, encoded) + + assert wpistruct.pack(generated(value)) == encoded + assert unpacked == generated(value) + assert type(unpacked.value) is wpistruct.char + + +def test_generated_char_arrays_retain_utf8_nul_and_padding_behavior(): + generated = make_wpistruct_from_schema( + "GeneratedCharArrays", "char singleton[1]; char text[4]", nested={} + ) + + utf8_value = generated("", "é") + nul_value = generated("\0", "a\0b") + + assert wpistruct.pack(utf8_value) == b"\0\xc3\xa9\0\0" + assert wpistruct.unpack(generated, b"\0\xc3\xa9\0\0") == utf8_value + assert wpistruct.pack(nul_value) == b"\0a\0b\0" + assert wpistruct.unpack(generated, b"\0a\0b\0") == generated("", "a\0b") + + +@pytest.mark.parametrize( + ("value", "cause_type"), + [ + ("", ValueError), + ("é", ValueError), + ("变量", ValueError), + (7, TypeError), + (None, TypeError), + ], +) +def test_generated_scalar_char_rejects_invalid_values_atomically(value, cause_type): + generated = make_wpistruct_from_schema( + "GeneratedInvalidChar", "char value", nested={} + ) + destination = bytearray(b"\xa5") + instance = generated(value) + + with pytest.raises( + ValueError, match="GeneratedInvalidChar.*error packing data" + ) as exc: + wpistruct.pack(instance) + assert isinstance(exc.value.__cause__, cause_type) + + with pytest.raises( + ValueError, match="GeneratedInvalidChar.*error packing data" + ) as exc: + generated.WPIStruct.pack_into(instance, destination) + assert isinstance(exc.value.__cause__, cause_type) + assert destination == b"\xa5" + + def test_generated_struct_name_is_not_executed_as_source(): generated = make_wpistruct_from_schema('Bad"Name', "uint8 value", nested={}) assert wpistruct.get_type_name(generated) == 'Bad"Name' diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py index 0de39d259..44d88847a 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_compiler.py @@ -323,20 +323,26 @@ def _schema_for_plans(plans: list[FieldPlan]) -> str: def _make_native_descriptor(struct_name: str, schema: str, plans: list[FieldPlan]): database = SchemaDatabase() - schemas: dict[str, str] = {} + descriptor = database.add(struct_name, schema) + if descriptor.is_valid: + return descriptor - def add_nested(type_string: str, nested_schema: str): - nested_name = type_string.removeprefix("struct:") - if schemas.get(nested_name) == nested_schema: - return - database.add(nested_name, nested_schema) - schemas[nested_name] = nested_schema + definitions = [] + seen_definitions = set() + + def collect_nested(type_string: str, nested_schema: str): + definition = (type_string.removeprefix("struct:"), nested_schema) + if definition not in seen_definitions: + seen_definitions.add(definition) + definitions.append(definition) for plan in plans: if plan.nested_type is not None: - wpistruct.for_each_nested(plan.nested_type, add_nested) + wpistruct.for_each_nested(plan.nested_type, collect_nested) - return database.add(struct_name, schema) + if definitions: + database.add_all(definitions) + return descriptor def _layout_python_names(native_fields, plans, python_names): @@ -406,7 +412,7 @@ def _descriptor_pack_element(plan: FieldPlan, value): def _descriptor_pack_value(plan: FieldPlan, value): if plan.is_char: - return value + return value if plan.is_array else char(value) if plan.is_array: if plan.enum_type is not None or plan.nested_type is not None: values = tuple(_descriptor_pack_element(plan, item) for item in value) From 4b3d4eeab7401ab5559ba7be923bace00fcc1c66 Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Tue, 18 Aug 2026 04:49:05 +0000 Subject: [PATCH 10/14] fix(wpiutil): normalize generated identifiers --- .../tests/test_struct_schema.py | 152 +++++++++++++++++- .../wpiutil/wpistruct/_schema.py | 4 +- 2 files changed, 154 insertions(+), 2 deletions(-) diff --git a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py index c9a7b5c34..95113a168 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py @@ -1,6 +1,7 @@ import dataclasses import enum import gc +import inspect import typing import pytest @@ -101,7 +102,7 @@ def test_generated_struct_name_is_not_executed_as_source(): def test_generated_struct_name_is_always_a_valid_identifier(): generated = make_wpistruct_from_schema("¼", "uint8 value", nested={}) - assert generated.__name__ == "_" + assert generated.__name__ == "_1_4" assert generated.__name__.isidentifier() assert wpistruct.get_type_name(generated) == "¼" assert wpistruct.unpack(generated, b"\x07") == generated(7) @@ -681,6 +682,155 @@ def test_direct_generation_preserves_schema_error_taxonomy(): assert type(exc_info.value) is exception_type +def test_generated_nfkc_field_aliases_preserve_wire_names_and_round_trip(): + schema = "uint8 K; uint16 foo; int8 e\u0301; bool 变量" + generated = make_wpistruct_from_schema("NFKCFields", schema, nested={}) + + assert [field.name for field in dataclasses.fields(generated)] == [ + "K", + "foo", + "é", + "变量", + ] + assert list(inspect.signature(generated).parameters) == ["K", "foo", "é", "变量"] + positional = generated(1, 0x0302, -2, True) + keyword_value = generated(**{"K": 1, "foo": 0x0302, "é": -2, "变量": True}) + encoded = b"\x01\x02\x03\xfe\x01" + + assert positional == keyword_value + assert repr(positional) == "NFKCFields(K=1, foo=770, é=-2, 变量=True)" + assert dataclasses.asdict(positional) == { + "K": 1, + "foo": 0x0302, + "é": -2, + "变量": True, + } + assert wpistruct.pack(positional) == encoded + assert wpistruct.unpack(generated, encoded) == positional + assert wpistruct.get_schema(generated) == schema + assert generated.__wpistruct_descriptor__.schema == schema + assert [ + (field.schema_name, field.python_name) + for field in generated.__wpistruct_descriptor__.fields + ] == [("K", "K"), ("foo", "foo"), ("e\u0301", "é"), ("变量", "变量")] + + +def test_generated_nfkc_field_collisions_and_keyword_are_deterministic(): + schema = "uint8 K; uint8 K; uint8 foo; uint8 foo; uint8 class" + generated = make_wpistruct_from_schema("NFKCCollisions", schema, nested={}) + aliases = ["K", "K_2", "foo", "foo_2", "class_"] + + assert [field.name for field in dataclasses.fields(generated)] == aliases + assert list(inspect.signature(generated).parameters) == aliases + positional = generated(1, 2, 3, 4, 5) + keyword_value = generated(**{"K": 1, "K_2": 2, "foo": 3, "foo_2": 4, "class_": 5}) + + assert positional == keyword_value + assert dataclasses.asdict(positional) == { + "K": 1, + "K_2": 2, + "foo": 3, + "foo_2": 4, + "class_": 5, + } + assert wpistruct.pack(positional) == b"\x01\x02\x03\x04\x05" + assert wpistruct.unpack(generated, b"\x01\x02\x03\x04\x05") == positional + assert wpistruct.get_schema(generated) == schema + assert [ + (field.schema_name, field.python_name) + for field in generated.__wpistruct_descriptor__.fields + ] == [ + ("K", "K"), + ("K", "K_2"), + ("foo", "foo"), + ("foo", "foo_2"), + ("class", "class_"), + ] + + +@pytest.mark.parametrize( + ("wire_name", "python_name"), + [ + ("pkg::K", "K"), + ("pkg::foo", "foo"), + ("pkg::e\u0301", "é"), + ("pkg::class", "class_"), + ("pkg::变量", "变量"), + ("pkg::WPIStruct", "WPIStruct"), + ], +) +def test_generated_nfkc_class_alias_preserves_exact_wire_name(wire_name, python_name): + generated = make_wpistruct_from_schema(wire_name, "uint8 value", nested={}) + value = generated(7) + + assert generated.__name__ == python_name + assert wpistruct.get_type_name(generated) == wire_name + assert generated.__wpistruct_descriptor__.type_name == wire_name + assert wpistruct.get_schema(generated) == "uint8 value" + assert wpistruct.pack(value) == b"\x07" + assert wpistruct.unpack(generated, b"\x07") == value + + +def test_generated_nfkc_enum_aliases_preserve_wire_metadata_and_round_trip(): + schema = "enum {K=1,K=2,class=3,变量=4} uint8 mode" + generated = make_wpistruct_from_schema("pkg::K", schema, nested={}) + mode_type = generated.__dataclass_fields__["mode"].type + + assert generated.__name__ == "K" + assert mode_type.__name__ == "KMode" + assert list(mode_type.__members__) == ["K", "K_2", "class_", "变量"] + assert [member.value for member in mode_type] == [1, 2, 3, 4] + for member in mode_type: + value = generated(member) + encoded = bytes([member.value]) + assert wpistruct.pack(value) == encoded + assert wpistruct.unpack(generated, encoded) == value + + layout = generated.__wpistruct_descriptor__ + assert wpistruct.get_type_name(generated) == "pkg::K" + assert wpistruct.get_schema(generated) == schema + assert layout.schema == schema + assert layout.fields[0].schema_name == "mode" + assert layout.fields[0].python_name == "mode" + assert layout.fields[0].enum_values == ( + ("K", 1), + ("K", 2), + ("class", 3), + ("变量", 4), + ) + + +def test_generated_nfkc_metadata_reservations_and_collisions(): + fullwidth_descriptor = "__wpistruct_descriptor__" + schema = ( + "uint8 WPIStruct; uint8 WPIStruct; " + f"uint8 {fullwidth_descriptor}; uint8 __wpistruct_descriptor__" + ) + generated = make_wpistruct_from_schema("NFKCMetadata", schema, nested={}) + aliases = [ + "WPIStruct_", + "WPIStruct_2", + "__wpistruct_descriptor___", + "__wpistruct_descriptor___2", + ] + value = generated(1, 2, 3, 4) + + assert [field.name for field in dataclasses.fields(generated)] == aliases + assert list(inspect.signature(generated).parameters) == aliases + assert wpistruct.pack(value) == b"\x01\x02\x03\x04" + assert wpistruct.unpack(generated, b"\x01\x02\x03\x04") == value + assert wpistruct.get_schema(generated) == schema + assert [ + (field.schema_name, field.python_name) + for field in generated.__wpistruct_descriptor__.fields + ] == [ + ("WPIStruct", "WPIStruct_"), + ("WPIStruct", "WPIStruct_2"), + (fullwidth_descriptor, "__wpistruct_descriptor___"), + ("__wpistruct_descriptor__", "__wpistruct_descriptor___2"), + ] + + def test_generated_and_registry_schemas_accept_authored_unicode_identifier(): schema = "uint8 é" generated = make_wpistruct_from_schema("DirectAuthoredUnicode", schema, nested={}) diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py index cbd07abeb..257c1ad8e 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py @@ -3,6 +3,7 @@ import keyword import re import typing +import unicodedata from .._wpiutil import wpistruct from .._wpiutil._schema import SchemaDatabase @@ -70,6 +71,7 @@ def __init__(self, type_name: str): def _sanitize_identifier(value: str) -> str: + value = unicodedata.normalize("NFKC", value) value = re.sub(r"\W", "_", value) if not value: value = "_" @@ -295,7 +297,7 @@ def make_wpistruct_from_schema( generated_tuple_elements = 0 compact_array_sizes: dict[str, int] = {} for field in descriptor.fields: - field_name = field.name + field_name = _sanitize_identifier(field.name) if field_name in _GENERATED_ATTRIBUTE_NAMES: field_name = f"{field_name}_" python_name = _unique_identifier(field_name, used_names) From d08347add2bcdaf376a0144b41309172f965b9f2 Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Tue, 18 Aug 2026 05:02:42 +0000 Subject: [PATCH 11/14] fix(wpiutil): preserve combining mark identifiers --- .../tests/test_struct_schema.py | 58 +++++++++++++++++-- .../wpiutil/wpistruct/_schema.py | 2 - 2 files changed, 54 insertions(+), 6 deletions(-) diff --git a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py index 95113a168..7c5e00236 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py @@ -2,6 +2,7 @@ import enum import gc import inspect +import re import typing import pytest @@ -164,8 +165,8 @@ def test_generated_explicit_singleton_arrays_preserve_tuple_values_and_bytes(): def test_many_scalar_fields_do_not_trigger_per_field_schema_scans(monkeypatch): scan_calls = 0 - original_compile = schema_module.re.compile - original_search = schema_module.re.search + original_compile = re.compile + original_search = re.search def counting_compile(pattern, *args, **kwargs): nonlocal scan_calls @@ -179,8 +180,8 @@ def counting_search(pattern, *args, **kwargs): scan_calls += 1 return original_search(pattern, *args, **kwargs) - monkeypatch.setattr(schema_module.re, "compile", counting_compile) - monkeypatch.setattr(schema_module.re, "search", counting_search) + monkeypatch.setattr(re, "compile", counting_compile) + monkeypatch.setattr(re, "search", counting_search) field_count = 256 schema = "; ".join(f"uint8 value{i}" for i in range(field_count)) @@ -682,6 +683,55 @@ def test_direct_generation_preserves_schema_error_taxonomy(): assert type(exc_info.value) is exception_type +def test_generated_nfkc_combining_mark_class_and_field_aliases_remain_exact(): + schema = "uint16 हिन्दी" + generated = make_wpistruct_from_schema("pkg::हिन्दी", schema, nested={}) + value = generated(0x1234) + encoded = b"\x34\x12" + + assert generated.__name__ == "हिन्दी" + assert [field.name for field in dataclasses.fields(generated)] == ["हिन्दी"] + assert wpistruct.get_type_name(generated) == "pkg::हिन्दी" + assert wpistruct.get_schema(generated) == schema + assert wpistruct.pack(value) == encoded + assert wpistruct.unpack(generated, encoded) == value + + layout = generated.__wpistruct_descriptor__ + assert layout.type_name == "pkg::हिन्दी" + assert layout.schema == schema + assert [(field.schema_name, field.python_name) for field in layout.fields] == [ + ("हिन्दी", "हिन्दी") + ] + + +def test_generated_identifier_repair_preserves_combining_marks_near_punctuation(): + wire_name = "pkg::हिन्दी-value" + generated = make_wpistruct_from_schema(wire_name, "uint8 value", nested={}) + value = generated(7) + + assert generated.__name__ == "हिन्दी_value" + assert wpistruct.get_type_name(generated) == wire_name + assert wpistruct.pack(value) == b"\x07" + assert wpistruct.unpack(generated, b"\x07") == value + + +def test_generated_nfkc_combining_mark_enum_alias_remains_exact(): + schema = "enum {हिन्दी=1} uint8 mode" + generated = make_wpistruct_from_schema("CombiningEnum", schema, nested={}) + mode_type = generated.__dataclass_fields__["mode"].type + value = generated(mode_type.__members__["हिन्दी"]) + encoded = b"\x01" + + assert list(mode_type.__members__) == ["हिन्दी"] + assert wpistruct.get_schema(generated) == schema + assert wpistruct.pack(value) == encoded + assert wpistruct.unpack(generated, encoded) == value + + field = generated.__wpistruct_descriptor__.fields[0] + assert (field.schema_name, field.python_name) == ("mode", "mode") + assert field.enum_values == (("हिन्दी", 1),) + + def test_generated_nfkc_field_aliases_preserve_wire_names_and_round_trip(): schema = "uint8 K; uint16 foo; int8 e\u0301; bool 变量" generated = make_wpistruct_from_schema("NFKCFields", schema, nested={}) diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py index 257c1ad8e..ca10c6ade 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py @@ -1,7 +1,6 @@ import dataclasses import enum import keyword -import re import typing import unicodedata @@ -72,7 +71,6 @@ def __init__(self, type_name: str): def _sanitize_identifier(value: str) -> str: value = unicodedata.normalize("NFKC", value) - value = re.sub(r"\W", "_", value) if not value: value = "_" if value[0].isdigit(): From 6c9d18a33d738aa77f8d6d936e9394614c209349 Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Tue, 18 Aug 2026 05:18:57 +0000 Subject: [PATCH 12/14] fix(wpiutil): reserve generated annotations field --- .../tests/test_struct_schema.py | 53 +++++++++++++++++++ .../wpiutil/wpistruct/_schema.py | 1 + 2 files changed, 54 insertions(+) diff --git a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py index 7c5e00236..107786942 100644 --- a/subprojects/robotpy-wpiutil/tests/test_struct_schema.py +++ b/subprojects/robotpy-wpiutil/tests/test_struct_schema.py @@ -402,6 +402,59 @@ def test_generated_metadata_reservation_does_not_change_other_identifiers(): assert wpistruct.get_type_name(generated) == "WPIStruct" +def test_generated_annotations_field_aliases_are_safe_and_deterministic(): + fullwidth_annotations = "__annotations__" + schema = ( + f"uint8 __annotations__; uint16 {fullwidth_annotations}; " + "uint32 __annotations___" + ) + generated = make_wpistruct_from_schema("AnnotationsFields", schema, nested={}) + aliases = ["__annotations___", "__annotations___2", "__annotations___3"] + + assert [field.name for field in dataclasses.fields(generated)] == aliases + assert list(inspect.signature(generated).parameters) == aliases + positional = generated(1, 0x0302, 0x07060504) + keyword_value = generated( + **{ + "__annotations___": 1, + "__annotations___2": 0x0302, + "__annotations___3": 0x07060504, + } + ) + encoded = b"\x01\x02\x03\x04\x05\x06\x07" + + assert positional == keyword_value + assert dataclasses.asdict(positional) == { + "__annotations___": 1, + "__annotations___2": 0x0302, + "__annotations___3": 0x07060504, + } + assert wpistruct.pack(positional) == encoded + assert wpistruct.unpack(generated, encoded) == positional + assert wpistruct.get_type_name(generated) == "AnnotationsFields" + assert wpistruct.get_schema(generated) == schema + + layout = generated.__wpistruct_descriptor__ + assert layout.type_name == "AnnotationsFields" + assert layout.schema == schema + assert [(field.schema_name, field.python_name) for field in layout.fields] == [ + ("__annotations__", "__annotations___"), + (fullwidth_annotations, "__annotations___2"), + ("__annotations___", "__annotations___3"), + ] + + +def test_generated_annotations_reservation_is_field_only(): + generated = make_wpistruct_from_schema( + "__annotations__", "enum {VALUE=1} uint8 mode", nested={} + ) + mode_type = generated.__dataclass_fields__["mode"].type + + assert generated.__name__ == "__annotations__" + assert mode_type.__name__ == "__annotations__Mode" + assert wpistruct.get_type_name(generated) == "__annotations__" + + def test_generated_serializer_metadata_names_are_sanitized(): generated = make_wpistruct_from_schema( "MetadataFields", diff --git a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py index ca10c6ade..1e4fd5c55 100644 --- a/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py +++ b/subprojects/robotpy-wpiutil/wpiutil/wpistruct/_schema.py @@ -44,6 +44,7 @@ def __init__(self, type_name: str): _GENERATED_ATTRIBUTE_NAMES = { "WPIStruct", + "__annotations__", "__wpistruct_descriptor__", } From ad72a9722910222a1e12cfa682e0110fe1f233da Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Thu, 20 Aug 2026 00:32:45 -0400 Subject: [PATCH 13/14] Fix CI --- subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml b/subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml index 436a67386..17d8b4b0b 100644 --- a/subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml +++ b/subprojects/robotpy-wpiutil/semiwrap/WPyStructSchema.yml @@ -38,8 +38,6 @@ classes: access: readonly wpy::structs::SchemaDescriptor: methods: - SchemaDescriptor: - ignore: true GetName: no_release_gil: true GetSchema: From 0261fa00bf9c9506dfa80893b2607e005e88d7a6 Mon Sep 17 00:00:00 2001 From: Dustin Spicuzza Date: Mon, 19 Oct 2026 04:49:34 +0000 Subject: [PATCH 14/14] Use synchronous writer in datalog example --- examples/datalog/writelog.py | 48 ++------------ .../tests/test_datalog_examples.py | 66 +++++++++++-------- 2 files changed, 46 insertions(+), 68 deletions(-) diff --git a/examples/datalog/writelog.py b/examples/datalog/writelog.py index cbb9d6e9c..8d0ff9f9d 100755 --- a/examples/datalog/writelog.py +++ b/examples/datalog/writelog.py @@ -2,52 +2,22 @@ import argparse import pathlib -import time +import uuid import wpilog from datalog_struct import ExampleRecord - -def _wait_for_complete_log(candidate_paths): - deadline = time.monotonic() + 5 - while True: - for path in candidate_paths(): - try: - values = wpilog.DataLogReader(str(path)).iter_auto(ExampleRecord) - record_count = sum( - entry is not None and entry.name == "/record" - for _, entry, _ in values - ) - except (OSError, ValueError): - continue - if record_count == 2: - return - - if time.monotonic() >= deadline: - raise TimeoutError("timed out waiting for the data log to flush") - time.sleep(0.01) - - if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("out", type=pathlib.Path) args = parser.parse_args() - if args.out.is_dir(): - existing_paths = set(args.out.iterdir()) - datalog = wpilog.DataLogBackgroundWriter(str(args.out)) - - def candidate_paths(): - return set(args.out.iterdir()) - existing_paths - - else: - datalog = wpilog.DataLogBackgroundWriter(str(args.out.parent), args.out.name) - - def candidate_paths(): - return (args.out,) + output = args.out + if output.is_dir(): + output = output / f"wpilog_{uuid.uuid4().hex}.wpilog" + datalog = wpilog.DataLogWriter(str(output)) - completed = False try: bools = wpilog.BooleanLogEntry(datalog, "/bools") bools.append(True) @@ -64,11 +34,5 @@ def candidate_paths(): record = wpilog.StructLogEntry(datalog, "/record", ExampleRecord) record.append(ExampleRecord(1, 2)) record.append(ExampleRecord(3, 4)) - completed = True finally: - try: - if completed: - datalog.flush() - _wait_for_complete_log(candidate_paths) - finally: - datalog.stop() + datalog.flush() diff --git a/subprojects/robotpy-wpilog/tests/test_datalog_examples.py b/subprojects/robotpy-wpilog/tests/test_datalog_examples.py index ff4bf6ad5..dd75ae294 100644 --- a/subprojects/robotpy-wpilog/tests/test_datalog_examples.py +++ b/subprojects/robotpy-wpilog/tests/test_datalog_examples.py @@ -1,7 +1,6 @@ import runpy import subprocess import sys -import types from pathlib import Path import pytest @@ -10,32 +9,49 @@ EXAMPLE_DIR = Path(__file__).parents[3] / "examples" / "datalog" -def test_writelog_output_is_immediately_readable(tmp_path): - output = tmp_path / "example.wpilog" +@pytest.mark.parametrize("directory", [False, True]) +def test_writelog_then_printlog(tmp_path, directory): + output = tmp_path if directory else tmp_path / "example.wpilog" subprocess.run( [sys.executable, str(EXAMPLE_DIR / "writelog.py"), str(output)], check=True, timeout=10, ) + if directory: + (output,) = tmp_path.glob("*.wpilog") values = list(wpilog.DataLogReader(str(output)).iter_auto()) - assert ( - sum(entry is not None and entry.name == "/record" for _, entry, _ in values) - == 2 - ) - + records = [ + value + for _, entry, value in values + if entry is not None and entry.name == "/record" + ] + assert [(value.i, value.j) for value in records] == [(1, 2), (3, 4)] -def test_writelog_stops_background_writer_when_append_fails(monkeypatch, tmp_path): - writers = [] + for options in ([], ["--predefined"]): + result = subprocess.run( + [sys.executable, str(EXAMPLE_DIR / "printlog.py"), *options, str(output)], + check=True, + capture_output=True, + text=True, + timeout=10, + ) + lines = result.stdout.splitlines() + for name, expected in ( + ("/bools", ["True", "False"]), + ("/strings", ["['a', 'b', 'c']", "['d', 'e', 'f']"]), + ("/raws", [repr(b"\x01\x02\x03"), repr(b"\x04\x05\x06")]), + ("/record", ["ExampleRecord(i=1, j=2)", "ExampleRecord(i=3, j=4)"]), + ): + entries = [line for line in lines if line.startswith(f"{name} [")] + assert len(entries) == len(expected) + for line, value in zip(entries, expected): + assert line.endswith(f"] {value}") - class FakeWriter: - def __init__(self, *args): - self.stopped = False - writers.append(self) - def stop(self): - self.stopped = True +def test_writelog_flushes_when_append_fails(monkeypatch, tmp_path): + output = tmp_path / "example.wpilog" class FailingEntry: def __init__(self, *args): @@ -44,18 +60,16 @@ def __init__(self, *args): def append(self, value): raise RuntimeError("intentional append failure") - fake_wpilog = types.ModuleType("wpilog") - fake_wpilog.DataLogBackgroundWriter = FakeWriter - fake_wpilog.BooleanLogEntry = FailingEntry - fake_wpilog.StringArrayLogEntry = FailingEntry - fake_wpilog.RawLogEntry = FailingEntry - fake_wpilog.StructLogEntry = FailingEntry - monkeypatch.setitem(sys.modules, "wpilog", fake_wpilog) + monkeypatch.setattr(wpilog, "StringArrayLogEntry", FailingEntry) monkeypatch.syspath_prepend(str(EXAMPLE_DIR)) - monkeypatch.setattr(sys, "argv", ["writelog.py", str(tmp_path / "example.wpilog")]) + monkeypatch.setattr(sys, "argv", ["writelog.py", str(output)]) with pytest.raises(RuntimeError, match="intentional append failure"): runpy.run_path(str(EXAMPLE_DIR / "writelog.py"), run_name="__main__") - assert len(writers) == 1 - assert writers[0].stopped + values = list(wpilog.DataLogReader(str(output)).iter_auto()) + assert [ + value + for _, entry, value in values + if entry is not None and entry.name == "/bools" + ] == [True, False]