diff --git a/lib/binary_parser.ts b/lib/binary_parser.ts index 230d16b..57f8257 100644 --- a/lib/binary_parser.ts +++ b/lib/binary_parser.ts @@ -1766,15 +1766,30 @@ export class Parser { if (this.options.type instanceof Parser) { if (this.varName) { ctx.pushCode(`${wrapperVar} = ${this.options.type.newObject(ctx)};`); + if (ctx.useContextVariables) { + const parentVar = ctx.generateVariable(); + ctx.pushCode(`${wrapperVar}.$parent = ${parentVar};`); + ctx.pushCode(`${wrapperVar}.$root = ${parentVar}.$root;`); + } } ctx.pushPath(this.varName); this.options.type.generate(ctx); ctx.popPath(this.varName); + if (this.varName && ctx.useContextVariables) { + ctx.pushCode(`delete ${wrapperVar}.$parent;`); + ctx.pushCode(`delete ${wrapperVar}.$root;`); + } } else if (aliasRegistry.has(this.options.type!)) { const tempVar = ctx.generateTmpVariable(); ctx.pushCode( - `var ${tempVar} = ${FUNCTION_PREFIX + this.options.type}(0);`, + `var ${tempVar} = ${FUNCTION_PREFIX + this.options.type}(0, {`, ); + if (ctx.useContextVariables) { + const parentVar = ctx.generateVariable(); + ctx.pushCode(`$parent: ${parentVar},`); + ctx.pushCode(`$root: ${parentVar}.$root,`); + } + ctx.pushCode("});"); ctx.pushCode(`${wrapperVar} = ${tempVar}.result;`); if (this.options.type !== this.alias) { ctx.addReference(this.options.type!); diff --git a/test/wrapper_context.ts b/test/wrapper_context.ts new file mode 100644 index 0000000..a07c640 --- /dev/null +++ b/test/wrapper_context.ts @@ -0,0 +1,47 @@ +import { Parser } from "../lib/binary_parser"; + +describe("wrapped parser context", () => { + for (const aliased of [false, true]) { + it(`preserves parent and root for ${aliased ? "named" : "inline"} types`, () => { + const child = new Parser().uint8("value", { + formatter(this: any, value) { + return { value, parent: this.$parent.tag, root: this.$root.rootTag }; + }, + }); + const type = aliased + ? child.namely("wrapper_context_child").alias! + : child; + const parent = new Parser().uint8("tag").wrapped("child", { + length: 1, + wrapper: (bytes) => bytes, + type, + }); + const parser = new Parser() + .useContextVars() + .uint8("rootTag") + .nest("parent", { type: parent }); + expect(parser.parse(new Uint8Array([3, 4, 5]))).toStrictEqual({ + rootTag: 3, + parent: { tag: 4, child: { value: { value: 5, parent: 4, root: 3 } } }, + }); + }); + } + + it("leaves context disabled for inline wrapped types by default", () => { + const child = new Parser().uint8("value", { + formatter(this: any, value) { + expect(Object.hasOwn(this, "$parent")).toBe(false); + expect(Object.hasOwn(this, "$root")).toBe(false); + return value; + }, + }); + const parser = new Parser().wrapped("child", { + type: child, + length: 1, + wrapper: (bytes) => bytes, + }); + expect(parser.parse(new Uint8Array([5]))).toStrictEqual({ + child: { value: 5 }, + }); + }); +});