Skip to content

Call wrapper functions with the current context as this - #339

Merged
keichi merged 1 commit into
keichi:masterfrom
imsurya26:fix/wrapper-context-this
Nov 20, 2026
Merged

keichi merged 1 commit into
keichi:masterfrom
imsurya26:fix/wrapper-context-this

Conversation

@imsurya26

Copy link
Copy Markdown
Contributor

Fixes #263.

generateWrapper() emits func.call(this, buffer). Inside the generated parser function this is whatever called the compiled parser, not the object being parsed. Formatters, assert and readUntil callbacks already receive the current context (ctx.generateVariable()), so a wrapper couldn't read sibling fields, e.g. a key parsed before the wrapped data:

new Parser()
  .uint8("key")
  .wrapped("data", {
    length: 2,
    wrapper: function (buf) {
      return buf.map((b) => b ^ this.key); // this.key was undefined
    },
    type: new Parser().uint8("a").uint8("b"),
  });

This change passes ctx.generateVariable() as this, as the issue suggests and as the other callbacks already do. In nested nest/array cases the wrapper sees the object currently being built. With useContextVars() that object also has $parent/$root/$index, as for formatters. Arrow-function wrappers ignore this and are unaffected.

Test: new "should call wrapper with the current context as this" in test/composite_parser.ts (runs for Buffer and Uint8Array). It fails without the change (a: 5 instead of 6) and passes with it. npm test: all passed. npm run format and tsc --noEmit clean.

generateWrapper() emitted func.call(this, ...), so a wrapper saw whatever called the compiled parser as this, while formatters, assert and readUntil callbacks get the current parse context. Use ctx.generateVariable() like them, so a wrapper can read sibling fields (e.g. a key parsed before the wrapped data). Fixes keichi#263.
@keichi

keichi commented Nov 20, 2026

Copy link
Copy Markdown
Owner

LGTM, thank you!

@keichi
keichi merged commit 25a5910 into keichi:master Nov 20, 2026
6 checks passed
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.

.wrapped wrapper should get access to context data

2 participants