Skip to content

feat(craft): add the binary format - #25

Merged
innkuika merged 2 commits into
craft/engine-namesfrom
craft/engine-binary
Dec 3, 2026
Merged

innkuika merged 2 commits into
craft/engine-namesfrom
craft/engine-binary

Conversation

@innkuika

@innkuika innkuika commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds the binary format to the Craft engine core: the compact form a host ships and loads at runtime. Stacked on #24. As in the other engine PRs, it has a blueprint, conformance cases and the code.

  • Blueprint: craft/blueprints/features/craft_binary_format.blueprint.md, a byte-level, language-agnostic spec: signatures, versioning and compatibility, every tag and encoding, declaration flags, extension tags and error kinds with offsets. It is complete enough that an independent reviewer wrote a decoder from it alone; that decoder agreed with the Dart decoder on all cases and on 200,000 random and mutated blobs.
  • Code: lib/src/rfw/binary.dart, forked from RFW 2.0.0:
    • Yegor's encodings for theme, media and symbol references (yjbanov/a2ui_craft at aece53f);
    • a versioned format: Craft signatures with a version and a minimum reader version. RFW blobs still decode as version 0;
    • a flags field on declarations (bit 0 = exported);
    • extension tags (0x80–0xEF) that older readers skip; other unknown tags are rejected;
    • typed errors with offsets; lengths are checked before anything is allocated;
    • new rules: repeated map keys and switch cases are rejected, and a leading byte order mark is preserved. The blueprint lists where this differs from RFW's decoder.
  • Tests:
    • 98 conformance cases in craft/conformance/craft/craft_binary_format.yaml, with annotated hex. They include encoder cases (source → exact bytes, round trip, re-encode) and decoder cases (bytes → canonical JSON or error kind and offset).
    • RFW 2.0.0's binary tests (32) pass. The only changes are that expected encodings now start with the Craft header, and the changes needed to run outside Flutter; the file header lists them.

An independent review checked the blueprint against the tests and the code, including mutations and the independent decoder.

Next: the language additions (conditional elements, local values, handler calls and more).

Pre-launch Checklist

One time:

For this PR:

  • I updated/added relevant documentation.
  • My code changes (if any) have tests.
  • License checks pass (python3 ./scripts/fix_licenses.py --check).
  • Format checks pass (./scripts/fix_format.sh --check).

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements the Craft binary format feature for the Dart codebase (a2ui_craft), introducing a comprehensive binary encoder and decoder along with extensive unit and conformance tests. The feedback highlights several critical issues and improvement opportunities in the implementation: a potential runtime crash when calling double.truncateToDouble() on non-finite values during switch case lookups, a potential ArgumentError on web platforms when passing large integers to ByteData.setInt32 without truncation, a readability concern regarding operator precedence in bitwise operations, and a redundant cast that can be simplified. Additionally, it is recommended to add test coverage for non-finite double values in switch lookups.

Comment on lines +248 to +252
bool _isExactly(double d, int i) =>
d == d.truncateToDouble() &&
d >= -9223372036854775808.0 &&
d < 9223372036854775808.0 &&
d.toInt() == i;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

In Dart, calling double.truncateToDouble() on non-finite values (double.nan, double.infinity, or double.negativeInfinity) throws an UnsupportedError. If a switch case lookup is performed with a non-finite double value, _sameCaseKey will invoke _isExactly, causing a runtime crash. To prevent this, we should guard the expression with d.isFinite to safely short-circuit for non-finite values.

bool _isExactly(double d, int i) =>\n    d.isFinite &&\n    d == d.truncateToDouble() &&\n    d >= -9223372036854775808.0 &&\n    d < 9223372036854775808.0 &&\n    d.toInt() == i;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

truncateToDouble() doesn't throw for NaN or ±Infinity; only truncate()/toInt() do. NaN fails the equality test and ±Infinity fails the range check before toInt(), so _isExactly returns false. Verified with a test.

Comment on lines +756 to +780
void _writeInt64(int value) {
if (_has64Bits) {
_scratchIn.setInt64(0, value, _blobEndian);
} else {
// We use division rather than bit shifts because >> truncates to 32 bits when compiled to JS:
// https://dart.dev/guides/language/numbers#bitwise-operations
if (value >= 0) {
// dead code on VM target
_scratchIn.setInt32(0, value, _blobEndian); // dead code on VM target
_scratchIn.setInt32(
4,
value ~/ 0x100000000,
_blobEndian,
); // dead code on VM target
} else {
_scratchIn.setInt32(0, value, _blobEndian); // dead code on VM target
_scratchIn.setInt32(
4,
-((-value) ~/ 0x100000000 + 1),
_blobEndian,
); // dead code on VM target
}
}
bytes.add(_scratchOut);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

In Dart, ByteData.setInt32 throws an ArgumentError if the value is not in the range [-2147483648, 2147483647]. On web platforms (where _has64Bits is false), value can be a 53-bit integer (e.g., largeNumber which is 9007199254730661). Passing this directly to _scratchIn.setInt32(0, value, _blobEndian) violates the API contract and will throw an ArgumentError on compliant Dart web runtimes. To prevent this, we should truncate value to a 32-bit signed integer using value.toSigned(32) before passing it to setInt32.

  void _writeInt64(int value) {\n    if (_has64Bits) {\n      _scratchIn.setInt64(0, value, _blobEndian);\n    } else {\n      // We use division rather than bit shifts because >> truncates to 32 bits when compiled to JS:\n      // https://dart.dev/guides/language/numbers#bitwise-operations\n      final int lower32 = value.toSigned(32);\n      if (value >= 0) {\n        // dead code on VM target\n        _scratchIn.setInt32(0, lower32, _blobEndian); // dead code on VM target\n        _scratchIn.setInt32(\n          4,\n          value ~/ 0x100000000,\n          _blobEndian,\n        ); // dead code on VM target\n      } else {\n        _scratchIn.setInt32(0, lower32, _blobEndian); // dead code on VM target\n        _scratchIn.setInt32(\n          4,\n          -((-value) ~/ 0x100000000 + 1),\n          _blobEndian,\n        ); // dead code on VM target\n      }\n    }\n    bytes.add(_scratchOut);\n  }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is RFW 2.0.0's code, unchanged, and it only runs on dart2js, where setInt32 wraps to 32 bits. Large positive and negative ints round-trip under dart test -p node. Not changing the fork here.

Comment on lines +783 to +795
for (var index = 0; index < value.length; index += 1) {
final int unit = value.codeUnitAt(index);
if (unit & 0xFC00 == 0xD800 &&
index + 1 < value.length &&
value.codeUnitAt(index + 1) & 0xFC00 == 0xDC00) {
index += 1;
} else if (unit & 0xF800 == 0xD800) {
throw StateError(
'Unpaired surrogate 0x${unit.toRadixString(16).toUpperCase()} '
'while encoding blob; it has no UTF-8 encoding.',
);
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In Dart, bitwise operators (&) have higher precedence than equality operators (==), so unit & 0xFC00 == 0xD800 is evaluated as (unit & 0xFC00) == 0xD800. However, in many other languages (like JavaScript, C, C++, Java), equality has higher precedence than bitwise AND, which makes this expression highly confusing and potentially error-prone for developers. Using explicit parentheses around the bitwise operations improves readability and ensures the code's intent is clear and robust.

    for (var index = 0; index < value.length; index += 1) {\n      final int unit = value.codeUnitAt(index);\n      if ((unit & 0xFC00) == 0xD800 &&\n          index + 1 < value.length &&\n          (value.codeUnitAt(index + 1) & 0xFC00) == 0xDC00) {\n        index += 1;\n      } else if ((unit & 0xF800) == 0xD800) {\n        throw StateError(\n          'Unpaired surrogate 0x${unit.toRadixString(16).toUpperCase()} '\n          'while encoding blob; it has no UTF-8 encoding.',\n        );\n      }\n    }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dart's precedence makes this correct as written (& binds tighter than ==); leaving it as is.

Comment on lines +913 to +918
} else if (value is SetStateHandler) {
bytes.addByte(_msSetState);
final reference = value.stateReference as StateReference;
_writeInt64(reference.parts.length);
reference.parts.forEach(_writePart);
_writeArgument(value.value);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The cast value.stateReference as StateReference is redundant. value.stateReference is of type AnyStateReference, which inherits from Reference. Since parts is defined on Reference, it can be accessed directly without casting. Removing this cast simplifies the code and avoids unnecessary runtime checks.

Suggested change
} else if (value is SetStateHandler) {
bytes.addByte(_msSetState);
final reference = value.stateReference as StateReference;
_writeInt64(reference.parts.length);
reference.parts.forEach(_writePart);
_writeArgument(value.value);
} else if (value is SetStateHandler) {\n bytes.addByte(_msSetState);\n final reference = value.stateReference;\n _writeInt64(reference.parts.length);\n reference.parts.forEach(_writePart);\n _writeArgument(value.value);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cast is intentional (it's RFW's own): stateReference can also be a runtime-only BoundStateReference, and the cast makes sure only an unbound reference gets encoded.

Comment on lines +71 to +77
test('an integer and a double that is exactly it are the same case', () {
final Switch value = decodeSwitch('9007199254740992: A(), 1: B()');
expect((value.outputs[9007199254740992.0]! as ConstructorCall).name, 'A');
expect((value.outputs[1.0]! as ConstructorCall).name, 'B');
});
});
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Let's add a test case to verify that looking up non-finite double values (like double.nan and double.infinity) in the decoded Switch outputs map does not throw an UnsupportedError.

    test('an integer and a double that is exactly it are the same case', () {\n      final Switch value = decodeSwitch('9007199254740992: A(), 1: B()');\n      expect((value.outputs[9007199254740992.0]! as ConstructorCall).name, 'A');\n      expect((value.outputs[1.0]! as ConstructorCall).name, 'B');\n    });\n\n    test('NaN and Infinity do not crash the decoder during lookup', () {\n      final Switch value = decodeSwitch('1: A()');\n      expect(value.outputs.containsKey(double.nan), isFalse);\n      expect(value.outputs.containsKey(double.infinity), isFalse);\n    });\n  });\n}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not needed: these lookups can't throw (see the reply on _isExactly).

Adds the craft_binary_format feature to craft/packages/a2ui_craft: the
byte-level encoding of libraries and data values, versioned and
extensible.

- lib/src/rfw/binary.dart is forked from RFW 2.0.0's binary encoder and
  decoder, starting from Yegor's version (yjbanov/a2ui_craft at
  aece53f), which adds tags 14-16 for theme, media and symbol
  references, and then the Craft prototype's versioned format:
  - Craft signatures FE 43 52 46 (library) and FE 43 52 44 (data), followed
    by a uint16 version and a uint16 minimum reader version (both 1). RFW
    signatures still decode, as version 0.
  - Version 1 declarations carry int64 flags; bit 0 is `export`, and
    decoders ignore unknown bits.
  - Tag ranges: 17-7F are future core tags and F0-FF reserved (both
    rejected); 80-EF are length-prefixed extension values that decoders
    skip as missing, leave out of data, and drop as switch case keys.
  - Every error is a BlobFormatException with a kind, a byte offset, the
    tag and the blob version; lengths are checked before allocating.
  New in this PR: repeated map keys and switch cases are rejected
  (duplicateKey) instead of silently replacing earlier ones, with switch
  cases compared and stored by the blueprint's exact equality (1 and 1.0
  are one case; the integer 2^53+1 and the double 2^53 are two), a leading byte
  order mark stays in its string, and the encoder rejects unpaired
  surrogates, which have no UTF-8 encoding. Error messages keep RFW's
  wording. craft/tool/diff_rfw.sh shows the diff against RFW.
- craft/blueprints/features/craft_binary_format.blueprint.md specifies
  the format byte by byte (signatures, versions, every tag, primitives,
  flags, extensions, errors and the round trip through the canonical
  JSON form).
- craft/conformance/craft/craft_binary_format.yaml holds 98 cases:
  decoder cases as annotated hex with the expected canonical form or
  error, and encoder cases that pin exact bytes and check the round
  trip. They include the prototype's 39 decoder fixtures and its format
  goldens (text to binary, and the RFW-signature blobs Craft wrote
  before the version header). test/conformance/binary_format_test.dart
  runs them.
- test/rfw/binary_test.dart is RFW 2.0.0's binary test, adapted to run
  outside Flutter and to the Craft signatures, header and flags, since the
  encoder no longer writes RFW blobs; the file header lists each change.
  Its byte arrays keep RFW's 16-per-line layout in dart format off regions.
- Conformance: the decode_library, decode_data, encode_library and
  encode_data actions and the F-CRAFT-BIN-01 to 11 feature IDs.

Co-authored-by: Yegor <yegor.jbanov@gmail.com>
@innkuika
innkuika force-pushed the craft/engine-binary branch from 50b95d2 to 70a151a Compare December 1, 2026 20:35

@ditman ditman left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Very impressive byte-level specification and implementation — the versioned header (version + minReaderVersion), skippable 0x80–0xEF extension tags, pre-allocation length checks (length > bytes.lengthInBytes - _cursor), typed BlobFormatException with offsets, and 98 annotated-hex conformance cases (plus RFW's 32 binary tests) are super thorough.

Approving to keep the stack moving — please address the items below (and the inline comments) in a follow-up PR down the line:

  1. Post-stack barrel tightening reminder (lib/a2ui_craft.dart): Per our agreement on #23, just a reminder to include src/rfw/binary.dart in the follow-up PR that switches the barrel to explicit show lists.
  2. dart2js int64 encoding bug for negative multiples of 2^32 (binary.dart): Inherited from RFW 2.0.0's JS fallback in _writeInt64: -((-value) ~/ 0x100000000 + 1) is off by 1 when value < 0 and value % 0x100000000 == 0 (e.g., -4294967296 encodes high word -2 and decodes back as -8589934592). Worth fixing in the fork with -((-value - 1) ~/ 0x100000000 + 1) if JS round-tripping matters; regression test inline.
  3. Minor nits: encoding initialState with writeValue instead of _writeArgument so programmatic non-data ASTs fail at encode time rather than decode time (test inline), and asserting expected.length == 1 in _runDecoderCase.

(Also noted that unbounded recursion depth on adversarial binary blobs is intentionally handled by maxDepth/maxNodes/maxSourceBytes in #33, so I did not flag missing depth limits as a blocker here.)


export 'src/canonical_json.dart';
export 'src/name_resolution.dart';
export 'src/rfw/binary.dart';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder for the post-stack barrel-tightening pass agreed in #23: please include src/rfw/binary.dart when switching the barrel to explicit show lists (e.g., blobFormatVersion, dataBlobSignature, libraryBlobSignature, legacyDataBlobSignature, legacyLibraryBlobSignature, BlobErrorKind, BlobFormatException, encodeDataBlob, decodeDataBlob, encodeLibraryBlob, decodeLibraryBlob).

Comment on lines +768 to +776
_blobEndian,
); // dead code on VM target
} else {
_scratchIn.setInt32(0, value, _blobEndian); // dead code on VM target
_scratchIn.setInt32(
4,
-((-value) ~/ 0x100000000 + 1),
_blobEndian,
); // dead code on VM target

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Note a subtle bug inherited from RFW 2.0.0 in this JS (_has64Bits == false) branch: for any negative multiple of 2^32 (e.g., -4294967296 = -0x100000000), -((-value) ~/ 0x100000000 + 1) evaluates to -2 (0xFFFFFFFE) instead of -1 (0xFFFFFFFF), so -4294967296 encodes as 00 00 00 00 FE FF FF FF and decodes back as -8589934592 (-2^33). (-largeNumber in binary_test.dart passes only because it isn't divisible by 2^32.)

Changing line 774 to -((-value - 1) ~/ 0x100000000 + 1) (or (value / 0x100000000).floor()) fixes all negative multiples of 2^32 while preserving -1, -0xFFFFFFFF, and -0x100000001. Totally fine to leave untouched if you want zero divergence from RFW's JS path, or fix here and add -0x100000000 to the web round-trip tests.

Drop-in regression test for test/rfw/binary_test.dart (fails under dart2js / -p chrome before fix, passes after):

test('Negative multiples of 2^32 round-trip', () {
  for (final int expected in <int>[
    -0x100000000, // -4294967296 (-2^32)
    -0x200000000, // -8589934592 (-2^33)
    -0x100000001, // -4294967297 (-2^32 - 1)
  ]) {
    final Uint8List bytes = encodeDataBlob(expected);
    final Object decoded = decodeDataBlob(bytes);
    expect(decoded, isA<int>());
    expect(decoded, expected);
  }
});

Comment on lines +932 to +934
if (declaration.initialState != null) {
_writeMap(declaration.initialState!, _writeArgument);
} else {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Nit: _readDeclaration decodes initialState with _readValue (data values only), while _writeDeclarationList encodes it with _writeArgument (inherited from RFW). Using writeValue here ensures that programmatically constructed WidgetDeclarations containing non-data nodes in initialState fail immediately on encode rather than producing a blob that decodeLibraryBlob rejects with unexpectedTag.

Drop-in regression test for test/rfw/binary_test.dart (or test/binary_test.dart):

test('encodeLibraryBlob rejects non-data nodes in initialState', () {
  const library = RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[
    WidgetDeclaration(
      'root',
      <String, Object?>{'bad': ArgsReference(<Object>['x'])},
      ConstructorCall('Text', <String, Object?>{}),
    ),
  ]);
  expect(() => encodeLibraryBlob(library), throwsStateError);
});

Comment on lines +75 to +81
final Map<String, Object?> expected = c['expect']! as Map<String, Object?>;
assertKnownKeys(expected, <String>{
kind,
if (kind == 'library') 'source',
'error',
}, 'expect');
final Object? error = expected['error'];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Nit (same as parse_cases.dart in #23): asserting expect(expected, hasLength(1)) here (and in _runEncoderCase when 'error' is present) prevents a malformed case containing both 'error' and 'library'/'data' from silently ignoring the non-error key if run outside the JSON schema validator.

binary_test.dart wrote 2^53 + 1 as a literal, which dart2js rejects, so the
file did not compile for `dart test -p node`. It is now parsed, and the
test that needs it runs on the VM only, since JavaScript numbers cannot
hold it.
@innkuika
innkuika merged commit e81d910 into main Dec 3, 2026
21 checks passed
@innkuika
innkuika deleted the craft/engine-binary branch December 3, 2026 02:07
innkuika added a commit that referenced this pull request Dec 3, 2026
# Description

Adds four **language extensions** to the Craft text format. Stacked on
#25. Same three parts as the other engine PRs: a blueprint, conformance
cases and the code.

None of them adds a node kind, tag or binary-format version. Each parses
to calls, loops and switches that already exist:

| Syntax | Meaning | Parses to |
| --- | --- | --- |
| `absent` | the "no value" literal (unlike `null`, it is not dropped
from maps) | a call named `absent` with no arguments |
| `call H { M }` | apply a handler to arguments | a call named `call`
with `handler` and `arguments` |
| `...if C: E` | a conditional list element | a loop over `switch C {
true: [true], default: [] }` with body `E` |
| `let N = V, ... in R` | local values at the start of a declaration |
substituted at parse time; nothing of the binding stays in the library |

- **Blueprint**:
`craft/blueprints/features/craft_language_extensions.blueprint.md`. It
also lists exactly which previously valid sources change meaning (for
example `call(x: 1)` in a value position). How these constructs evaluate
is specified by the functions and runtime features.
- `absent` and `call` become reserved words and construct names. They
can't be loop variables, builder arguments or qualified names, and they
never resolve to a widget, so `libraries_and_names` is updated to match.
- **Tests**: 43 conformance cases with 71 sources. Every accepted
library also goes through the binary round trip, and every rejection has
a control case. The prototype's parse-level unit tests are ported.

An independent review checked the blueprints against the tests and the
code, including mutations and probes of previously valid sources.

Next: functions (host-registered pure functions and the standard
library).

## Pre-launch Checklist

One time:

- [x] I signed the [CLA].
- [x] I read the [Contributors Guide].

For this PR:

- [x] I updated/added relevant documentation.
- [x] My code changes (if any) have tests.
- [x] License checks pass (`python3 ./scripts/fix_licenses.py --check`).
- [x] Format checks pass (`./scripts/fix_format.sh --check`).

<!-- Links -->

[CLA]: https://cla.developers.google.com/
[Contributors Guide]:
https://github.com/a2ui-project/a2ui-labs/blob/main/CONTRIBUTING.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants