From d4ca9c94e7ee4ec0d5e008e976f71cd4c6a898b8 Mon Sep 17 00:00:00 2001 From: Y Date: Fri, 26 Feb 2021 05:36:09 -0500 Subject: [PATCH] fix: throw an explicit error when there is nothing to repeat --- assembly/__tests__/regex.spec.ts | 8 ++++++++ assembly/parser/parser.ts | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/assembly/__tests__/regex.spec.ts b/assembly/__tests__/regex.spec.ts index 691caed..e239556 100644 --- a/assembly/__tests__/regex.spec.ts +++ b/assembly/__tests__/regex.spec.ts @@ -155,3 +155,11 @@ describe("use cases", () => { expect(match.matches[3]).toBe("com"); }); }); + +describe("error cases", () => { + it("throws an explicit error when there is nothing to repeat", () => { + expect(() => { + let foo = new RegExp("*m", ""); // eslint-disable-line no-invalid-regexp + }).toThrow("Invalid regular expression: Nothing to repeat"); + }); +}); diff --git a/assembly/parser/parser.ts b/assembly/parser/parser.ts index dad0242..e13aa94 100644 --- a/assembly/parser/parser.ts +++ b/assembly/parser/parser.ts @@ -251,6 +251,10 @@ export class Parser { nodes.push(this.parseCharacter()); } } else if (isQuantifier(token)) { + if (nodes.length === 0) { + throw new Error("Invalid regular expression: Nothing to repeat"); + } + const expression = nodes.pop(); const quantifier = this.eatToken(); nodes.push(new RepetitionNode(expression, quantifier, this.isGreedy()));