Skip to content

Call assert functions with the enclosing object as this - #352

Open
keichi wants to merge 1 commit into
masterfrom
fix-assert-this
Open

keichi wants to merge 1 commit into
masterfrom
fix-assert-this

Conversation

@keichi

@keichi keichi commented Nov 22, 2026

Copy link
Copy Markdown
Owner

assert predicates were called with the top-level vars as this, while formatter, length, readUntil and wrapper callbacks get the object the field belongs to. So inside a nest, array item, choice or pointer, an assert could not see its sibling fields:

const item = new Parser().uint8("a").uint8("b").uint8("c", {
  assert(x) { return this.a + this.b === x; },
});
new Parser().nest("n", { type: item }).parse(Uint8Array.of(1, 2, 3));
// Error: Assertion error: vars.n.c is ... (this.a / this.b are undefined)

generateAssert now takes the this expression like generateFormatter, defaulting to the current scope. Deferred bit fields pass the scope captured when the field was queued, so they keep working when the bit run is flushed inside a nested parser.

Behavior is unchanged for top-level fields. Code that relied on this being the root object from inside a nested parser will break; useContextVars() + this.$root is the replacement.

Adds a regression test covering nest, array items and bit fields in a nest (fails on master).

Assert predicates were called with the top-level vars as this, so inside
nest, array items, choice and pointer they could not see sibling fields.
Bind this to the object the field belongs to, as formatter already does.
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.

1 participant