Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/binary_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -832,7 +832,9 @@ export class Parser {
private addAliasedCode(ctx: Context) {
ctx.pushCode(`function ${FUNCTION_PREFIX + this.alias}(offset, context) {`);
ctx.pushCode(
`var vars = ${this.constructorFn ? "new constructorFn()" : "{}"};`,
`var vars = ${
this.constructorFn ? `new ${ctx.addImport(this.constructorFn)}()` : "{}"
};`,
);
ctx.pushCode(
"var ctx = Object.assign({$parent: null, $root: vars}, context || {});",
Expand Down
34 changes: 34 additions & 0 deletions test/composite_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1050,6 +1050,40 @@ function compositeParserTests(
expect(person instanceof Person).toBeTruthy();
expect(person.name).toStrictEqual("John Doe");
});

it("should use the aliased parser's own constructor", () => {
class Foo {
isFoo = true;
}
class Bar {
isBar = true;
}

Parser.start().create(Foo).uint8("v").namely("ConstructorTestFoo");

const buffer = factory([1, 2]);
const plain = new Parser()
.nest("n", { type: "ConstructorTestFoo" })
.parse(buffer);
expect(plain.n instanceof Foo).toBeTruthy();
expect(plain.n.v).toStrictEqual(1);

const withBar = Parser.start()
.create(Bar)
.nest("n", { type: "ConstructorTestFoo" })
.parse(buffer);
expect(withBar instanceof Bar).toBeTruthy();
expect(withBar.n instanceof Foo).toBeTruthy();

const topLevel = Parser.start()
.create(Bar)
.uint8("a")
.nest("self", { type: "ConstructorTestFoo" })
.namely("ConstructorTestTop");
const result = topLevel.parse(buffer);
expect(result instanceof Bar).toBeTruthy();
expect(result.self instanceof Foo).toBeTruthy();
});
});

describe("Pointer parser", () => {
Expand Down
Loading