-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathencoder.ts
71 lines (58 loc) · 1.87 KB
/
encoder.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import type { RegexElement } from './types';
import { EncoderPriority, type EncoderNode } from './types-internal';
import { encodeChoiceOf } from './components/choiceOf';
import { encodeCharacterClass } from './character-classes/encoder';
import {
encodeOne,
encodeOneOrMore,
encodeOptionally,
encodeZeroOrMore,
} from './quantifiers/base';
import { encodeRepeat } from './quantifiers/repeat';
import { concatNodes, escapeText } from './utils';
export function encodeSequence(elements: RegexElement[]): EncoderNode {
return concatNodes(elements.map((c) => encodeElement(c)));
}
export function encodeElement(element: RegexElement): EncoderNode {
if (typeof element === 'string') {
return encodeText(element);
}
if (element.type === 'characterClass') {
return encodeCharacterClass(element);
}
if (element.type === 'choiceOf') {
return encodeChoiceOf(element, encodeElement);
}
if (element.type === 'repeat') {
return encodeRepeat(element.config, encodeSequence(element.children));
}
if (element.type === 'one') {
return encodeOne(encodeSequence(element.children));
}
if (element.type === 'oneOrMore') {
return encodeOneOrMore(encodeSequence(element.children));
}
if (element.type === 'optionally') {
return encodeOptionally(encodeSequence(element.children));
}
if (element.type === 'zeroOrMore') {
return encodeZeroOrMore(encodeSequence(element.children));
}
// @ts-expect-error User passed incorrect type
throw new Error(`Unknown elements type ${element.type}`);
}
function encodeText(text: string): EncoderNode {
if (text.length === 0) {
throw new Error('`encodeText`: received text should not be empty');
}
if (text.length === 1) {
return {
priority: EncoderPriority.Atom,
pattern: escapeText(text),
};
}
return {
priority: EncoderPriority.Sequence,
pattern: escapeText(text),
};
}