Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: improve tree shaking #98

Merged
merged 19 commits into from
Sep 9, 2024
Merged
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
20 changes: 12 additions & 8 deletions src/__tests__/builder.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { buildRegExp, char, unicodeProperty } from '..';
import { buildRegExp, unicodeChar, unicodeProperty } from '..';

test('`regexBuilder` flags', () => {
expect(buildRegExp('a').flags).toBe('');
Expand Down Expand Up @@ -34,22 +34,26 @@ test('`regexBuilder` flags', () => {
});

test('`regexBuilder` throws when using unicode-aware features without `unicode` flag', () => {
expect(() => buildRegExp(char(0x1234))).not.toThrow();
expect(() => buildRegExp(char(0x12345), { unicode: true })).not.toThrow();
expect(() => buildRegExp(unicodeChar(0x1234))).not.toThrow();
expect(() => buildRegExp(unicodeChar(0x12345), { unicode: true })).not.toThrow();
expect(() => buildRegExp(unicodeProperty('Emoji_Presentation'), { unicode: true })).not.toThrow();

expect(() => buildRegExp(char(0x123456))).toThrowErrorMatchingInlineSnapshot(
expect(() => buildRegExp(unicodeChar(0x123456))).toThrowErrorMatchingInlineSnapshot(
`"Expected a valid unicode code point but received 1193046"`,
);
expect(() => buildRegExp(char(0x12345))).toThrowErrorMatchingInlineSnapshot(
`"The pattern "\\u{12345}" requires Unicode-aware mode. Please ensure the "unicode" flag is set."`,
expect(() => buildRegExp(unicodeChar(0x12345))).toThrowErrorMatchingInlineSnapshot(
`"Pattern "\\u{12345}" requires "unicode" flag to be set."`,
);
expect(() =>
buildRegExp(unicodeProperty('Emoji_Presentation')),
).toThrowErrorMatchingInlineSnapshot(
`"The pattern "\\p{Emoji_Presentation}" requires Unicode-aware mode. Please ensure the "unicode" flag is set."`,
`"Pattern "\\p{Emoji_Presentation}" requires "unicode" flag to be set."`,
);
expect(() => buildRegExp(/\P{Letter}/u)).toThrowErrorMatchingInlineSnapshot(
`"The pattern "\\P{Letter}" requires Unicode-aware mode. Please ensure the "unicode" flag is set."`,
`"Pattern "\\P{Letter}" requires "unicode" flag to be set."`,
);
});

test('`regexBuilder` does not throws on tricky unicode mode-like patterns', () => {
expect(() => buildRegExp(/\\u{1234}/)).not.toThrow();
});
25 changes: 12 additions & 13 deletions src/builders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,9 @@ import { encode } from './encoder';
*/
export function buildRegExp(sequence: RegexSequence, flags?: RegexFlags): RegExp {
const pattern = encode(sequence).pattern;
const flagsString = encodeFlags(flags ?? {});

if (!flags?.unicode) {
const unicodeModePattern = getUnicodeModePattern(pattern);
if (unicodeModePattern) {
throw new Error(
`The pattern "${unicodeModePattern}" requires Unicode-aware mode. Please ensure the "unicode" flag is set.`,
);
}
}
ensureUnicodeFlagIfNeeded(pattern, flags);

const flagsString = encodeFlags(flags ?? {});
return new RegExp(pattern, flagsString);
}

Expand All @@ -47,9 +39,16 @@ function encodeFlags(flags: RegexFlags): string {
return result;
}

const unicodeModePatterns = /(?:\\u|\\p|\\P)\{.+?\}/;
// Matches unicode mode patterns: \u{...}, \p{...}, \P{...}, but avoids valid \\u{...}, etc
const unicodeModePatterns = /(?<!\\)(?:\\u|\\[pP])\{.+?\}/;

function ensureUnicodeFlagIfNeeded(pattern: string, flags: RegexFlags | undefined) {
if (flags?.unicode) {
return;
}

function getUnicodeModePattern(pattern: string): string | null {
const match = pattern.match(unicodeModePatterns);
return match?.[0] ?? null;
if (match) {
throw new Error(`Pattern "${match?.[0]}" requires "unicode" flag to be set.`);
}
}
33 changes: 15 additions & 18 deletions src/constructs/__tests__/char-class.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
anyOf,
buildRegExp,
charClass,
charRange,
digit,
Expand Down Expand Up @@ -38,9 +37,7 @@ test('`charClass` joins character escapes', () => {
});

test('`charClass` throws on empty text', () => {
expect(() => charClass()).toThrowErrorMatchingInlineSnapshot(
`"\`charClass\` should receive at least one element"`,
);
expect(() => charClass()).toThrowErrorMatchingInlineSnapshot(`"Expected at least one element"`);
});

test('`charRange` pattern', () => {
Expand All @@ -49,15 +46,23 @@ test('`charRange` pattern', () => {
expect([charRange('A', 'F'), 'x']).toEqualRegex(/[A-F]x/);
});

test('`charRange` works both ways', () => {
expect(charRange('a', 'z')).toEqualRegex(/[a-z]/);
expect(charRange('z', 'a')).toEqualRegex(/[a-z]/);
});

test('`charRange` throws on incorrect arguments', () => {
expect(() => charRange('z', 'a')).toThrowErrorMatchingInlineSnapshot(
`"\`start\` should be before or equal to \`end\`"`,
);
expect(() => charRange('aa', 'z')).toThrowErrorMatchingInlineSnapshot(
`"\`charRange\` should receive only single character \`start\` string"`,
`"Expected single characters, but received "aa" & "z""`,
);
expect(() => charRange('a', 'zz')).toThrowErrorMatchingInlineSnapshot(
`"\`charRange\` should receive only single character \`end\` string"`,
`"Expected single characters, but received "a" & "zz""`,
);
expect(() => charRange('', 'z')).toThrowErrorMatchingInlineSnapshot(
`"Expected single characters, but received "" & "z""`,
);
expect(() => charRange('a', '')).toThrowErrorMatchingInlineSnapshot(
`"Expected single characters, but received "a" & """`,
);
});

Expand Down Expand Up @@ -105,9 +110,7 @@ test('`anyOf` pattern edge cases', () => {
});

test('`anyOf` throws on empty text', () => {
expect(() => anyOf('')).toThrowErrorMatchingInlineSnapshot(
`"\`anyOf\` should received at least one character"`,
);
expect(() => anyOf('')).toThrowErrorMatchingInlineSnapshot(`"Expected at least one character"`);
});

test('`negated` character class pattern', () => {
Expand All @@ -119,9 +122,3 @@ test('`negated` character class matching', () => {
expect(negated(anyOf('a'))).not.toMatchString('aa');
expect(negated(anyOf('a'))).toMatchGroups('aba', ['b']);
});

test('`encodeCharacterClass` throws on empty text', () => {
expect(() => buildRegExp(negated({ chars: [], ranges: [] }))).toThrowErrorMatchingInlineSnapshot(
`"Character class should contain at least one character or character range"`,
);
});
2 changes: 1 addition & 1 deletion src/constructs/__tests__/choice-of.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@ test('`choiceOf` pattern using nested regex', () => {

test('`choiceOf` throws on empty options', () => {
expect(() => choiceOf()).toThrowErrorMatchingInlineSnapshot(
`"\`choiceOf\` should receive at least one alternative"`,
`"Expected at least one alternative"`,
);
});
4 changes: 2 additions & 2 deletions src/constructs/__tests__/encoder.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,14 @@ test('`buildRegExp` throws error on unknown element', () => {
// @ts-expect-error intentionally passing incorrect object
buildRegExp({ type: 'unknown' }),
).toThrowErrorMatchingInlineSnapshot(`
"\`encodeElement\`: unknown element: {
"Unsupported element. Received: {
"type": "unknown"
}"
`);
});

test('`buildPattern` throws on empty text', () => {
expect(() => buildPattern('')).toThrowErrorMatchingInlineSnapshot(
`"\`encodeText\`: received text should not be empty"`,
`"Expected at least one character"`,
);
});
4 changes: 1 addition & 3 deletions src/constructs/__tests__/repeat.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ test('`repeat` pattern optimizes grouping for atoms', () => {
});

test('`repeat` throws on no children', () => {
expect(() => repeat([], 1)).toThrowErrorMatchingInlineSnapshot(
`"\`repeat\` should receive at least one element"`,
);
expect(() => repeat([], 1)).toThrowErrorMatchingInlineSnapshot(`"Expected at least one element"`);
});

test('greedy `repeat` quantifier pattern', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,88 +5,99 @@ import {
endOfString,
type RegexSequence,
startOfString,
unicodeChar,
unicodeProperty,
} from '../..';

function u(sequence: RegexSequence) {
return buildRegExp(sequence, { unicode: true });
}

test('`char` pattern', () => {
test('`unicodeChar` pattern', () => {
// eslint-disable-next-line no-control-regex
expect(char(0)).toEqualRegex(/\u0000/);
expect(unicodeChar(0)).toEqualRegex(/\u0000/);
// eslint-disable-next-line no-control-regex
expect(char(0x1)).toEqualRegex(/\u0001/);
expect(unicodeChar(0x1)).toEqualRegex(/\u0001/);
// eslint-disable-next-line no-control-regex
expect(char(0x12)).toEqualRegex(/\u0012/);
expect(char(0x123)).toEqualRegex(/\u0123/);
expect(char(0x1234)).toEqualRegex(/\u1234/);
expect(unicodeChar(0x12)).toEqualRegex(/\u0012/);
expect(unicodeChar(0x123)).toEqualRegex(/\u0123/);
expect(unicodeChar(0x1234)).toEqualRegex(/\u1234/);

// eslint-disable-next-line no-control-regex
expect(u(char(0))).toEqualRegex(new RegExp('\\u0000', 'u'));
expect(u(unicodeChar(0))).toEqualRegex(new RegExp('\\u0000', 'u'));
// eslint-disable-next-line no-control-regex
expect(u(char(0x1))).toEqualRegex(new RegExp('\\u0001', 'u'));
expect(u(char(0x12))).toEqualRegex(
expect(u(unicodeChar(0x1))).toEqualRegex(new RegExp('\\u0001', 'u'));
expect(u(unicodeChar(0x12))).toEqualRegex(
// eslint-disable-next-line no-control-regex
new RegExp('\\u0012', 'u'),
);
expect(char(0x0123)).toEqualRegex(/\u0123/);
expect(char(0x1234)).toEqualRegex(/\u1234/);
expect(unicodeChar(0x0123)).toEqualRegex(/\u0123/);
expect(unicodeChar(0x1234)).toEqualRegex(/\u1234/);

expect(u(char(0x0123))).toEqualRegex(/\u0123/u);
expect(u(char(0x1234))).toEqualRegex(/\u1234/u);
expect(u(char(0x12345))).toEqualRegex(new RegExp('\\u{12345}', 'u'));
expect(u(char(0x103456))).toEqualRegex(new RegExp('\\u{103456}', 'u'));
expect(u(unicodeChar(0x0123))).toEqualRegex(/\u0123/u);
expect(u(unicodeChar(0x1234))).toEqualRegex(/\u1234/u);
expect(u(unicodeChar(0x12345))).toEqualRegex(new RegExp('\\u{12345}', 'u'));
expect(u(unicodeChar(0x103456))).toEqualRegex(new RegExp('\\u{103456}', 'u'));
});

test('`char` matching', () => {
expect(char(0)).toMatchString('\u{0}');
expect(char(0x1)).toMatchString('\u{1}');
expect(char(0x12)).toMatchString('\u{12}}');
expect(char(0x123)).toMatchString('\u{123}');
expect(char(0x1234)).toMatchString('\u{1234}}');

expect(char('a'.codePointAt(0)!)).toMatchString('a');
expect(char('ą'.codePointAt(0)!)).toMatchString('ą');
expect(char('©'.codePointAt(0)!)).toMatchString('©');

expect(u(char(0))).toMatchString('\u{0}');
expect(u(char(0))).not.toMatchString('a');
expect(u(char(0x1))).toMatchString('\u{1}');
expect(u(char(0x12))).toMatchString('\u{12}');
expect(u(char(0x123))).toMatchString('\u{123}');
expect(u(char(0x1234))).toMatchString('\u{1234}');
expect(u(char(0x12345))).toMatchString('\u{12345}');
expect(u(char(0x103456))).toMatchString('\u{103456}');

expect(u(char('a'.codePointAt(0)!))).toMatchString('a');
expect(u(char('ą'.codePointAt(0)!))).toMatchString('ą');
expect(u(char('©'.codePointAt(0)!))).toMatchString('©');
expect(u(char('😎'.codePointAt(0)!))).toMatchString('😎');
expect(u(char('😎'.codePointAt(0)!))).toMatchString('\u{1f60e}');
test('`unicodeChar` matching', () => {
expect(unicodeChar(0)).toMatchString('\u{0}');
expect(unicodeChar(0x1)).toMatchString('\u{1}');
expect(unicodeChar(0x12)).toMatchString('\u{12}}');
expect(unicodeChar(0x123)).toMatchString('\u{123}');
expect(unicodeChar(0x1234)).toMatchString('\u{1234}}');

expect(unicodeChar('a'.codePointAt(0)!)).toMatchString('a');
expect(unicodeChar('ą'.codePointAt(0)!)).toMatchString('ą');
expect(unicodeChar('©'.codePointAt(0)!)).toMatchString('©');

expect(u(unicodeChar(0))).toMatchString('\u{0}');
expect(u(unicodeChar(0))).not.toMatchString('a');
expect(u(unicodeChar(0x1))).toMatchString('\u{1}');
expect(u(unicodeChar(0x12))).toMatchString('\u{12}');
expect(u(unicodeChar(0x123))).toMatchString('\u{123}');
expect(u(unicodeChar(0x1234))).toMatchString('\u{1234}');
expect(u(unicodeChar(0x12345))).toMatchString('\u{12345}');
expect(u(unicodeChar(0x103456))).toMatchString('\u{103456}');

expect(u(unicodeChar('a'.codePointAt(0)!))).toMatchString('a');
expect(u(unicodeChar('ą'.codePointAt(0)!))).toMatchString('ą');
expect(u(unicodeChar('©'.codePointAt(0)!))).toMatchString('©');
expect(u(unicodeChar('😎'.codePointAt(0)!))).toMatchString('😎');
expect(u(unicodeChar('😎'.codePointAt(0)!))).toMatchString('\u{1f60e}');
});

test('`char` nesting matching', () => {
expect(u(charClass(char('a'.codePointAt(0)!), char('ą'.codePointAt(0)!)))).toMatchString('a');
expect(u(charClass(char('a'.codePointAt(0)!), char('ą'.codePointAt(0)!)))).toMatchString('ą');
expect(u(charClass(char('a'.codePointAt(0)!), char('ą'.codePointAt(0)!)))).not.toMatchString('b');
test('`unicodeChar` nesting matching', () => {
expect(
u(charClass(unicodeChar('a'.codePointAt(0)!), unicodeChar('ą'.codePointAt(0)!))),
).toMatchString('a');
expect(
u(charClass(unicodeChar('a'.codePointAt(0)!), unicodeChar('ą'.codePointAt(0)!))),
).toMatchString('ą');
expect(
u(charClass(unicodeChar('a'.codePointAt(0)!), unicodeChar('ą'.codePointAt(0)!))),
).not.toMatchString('b');
});

test('`char` edge cases handling', () => {
expect(() => u(char(NaN))).toThrowErrorMatchingInlineSnapshot(
test('`unicodeChar` edge cases handling', () => {
expect(() => u(unicodeChar(NaN))).toThrowErrorMatchingInlineSnapshot(
`"Expected a valid unicode code point but received NaN"`,
);
expect(() => u(char(1.5))).toThrowErrorMatchingInlineSnapshot(
expect(() => u(unicodeChar(1.5))).toThrowErrorMatchingInlineSnapshot(
`"Expected a valid unicode code point but received 1.5"`,
);
expect(() => u(char(-1))).toThrowErrorMatchingInlineSnapshot(
expect(() => u(unicodeChar(-1))).toThrowErrorMatchingInlineSnapshot(
`"Expected a valid unicode code point but received -1"`,
);
expect(() => u(char(0x110000))).toThrowErrorMatchingInlineSnapshot(
expect(() => u(unicodeChar(0x110000))).toThrowErrorMatchingInlineSnapshot(
`"Expected a valid unicode code point but received 1114112"`,
);

expect(u(char(0x10ffff))).toEqualRegex(/\u{10ffff}/u);
expect(u(unicodeChar(0x10ffff))).toEqualRegex(/\u{10ffff}/u);
});

test('"char" alias', () => {
expect(char('a'.codePointAt(0)!)).toEqualRegex(/\u0061/);
});

test('`unicodeProperty` pattern', () => {
Expand Down
Loading
Loading