diff --git a/lib/binary_parser.ts b/lib/binary_parser.ts index cf511f6..ff24295 100644 --- a/lib/binary_parser.ts +++ b/lib/binary_parser.ts @@ -644,6 +644,12 @@ export class Parser { throw new Error("length or readUntil must be defined for wrapped."); } + if (!(options.type instanceof Parser) && !varName) { + throw new Error( + "type must be a Parser object if the variable name is omitted.", + ); + } + return this.setNextParser("wrapper", varName as string, options); } @@ -702,6 +708,18 @@ export class Parser { ) { throw new Error(`Choice type "${value}" is unknown.`); } + + if (typeof value === "string" && !varName) { + throw new Error( + "Choice type must be a Parser object if the variable name is omitted.", + ); + } + } + + if (typeof options.defaultChoice === "string" && !varName) { + throw new Error( + "defaultChoice must be a Parser object if the variable name is omitted.", + ); } return this.setNextParser("choice", varName as string, options); diff --git a/test/composite_parser.ts b/test/composite_parser.ts index b369b54..40aa3b0 100644 --- a/test/composite_parser.ts +++ b/test/composite_parser.ts @@ -877,6 +877,27 @@ function compositeParserTests( }, }); }); + it("should throw if varName is omitted and a choice is a string", () => { + Parser.start().uint8("v").namely("choiceNoVarNameAlias"); + expect(() => + new Parser().uint8("tag").choice({ + tag: "tag", + choices: { 1: "choiceNoVarNameAlias" }, + }), + ).toThrow(); + expect(() => + new Parser() + .uint8("tag") + .choice({ tag: "tag", choices: { 1: "uint8" } }), + ).toThrow(); + expect(() => + new Parser().uint8("tag").choice({ + tag: "tag", + choices: { 1: Parser.start().uint8("v") }, + defaultChoice: "uint8", + }), + ).toThrow(); + }); }); describe("Nest parser", () => { @@ -1452,6 +1473,16 @@ function compositeParserTests( parserWithoutName.parse(buffer), ); }); + it("should throw if varName is omitted and type is a string", () => { + Parser.start().uint8("v").namely("wrappedNoVarNameAlias"); + expect(() => + new Parser().uint8("x").wrapped({ + length: 1, + wrapper: (b: Uint8Array) => b, + type: "wrappedNoVarNameAlias", + }), + ).toThrow(); + }); }); }); }