-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.js
109 lines (93 loc) · 3.08 KB
/
parser.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
const last = stack => stack[stack.length - 1];
function parse(re) {
const stack = [[]];
let i = 0;
while (i < re.length) {
const next = re[i];
switch (next) {
case '.': {
last(stack).push({
type: 'wildcard',
quantifier: 'exactlyOne',
});
i++
continue;
}
case '?': {
const lastElement = last(last(stack));
if (!lastElement || lastElement.quantifier !== 'exactlyOne') {
throw new Error('Quantifier must follow an unquantified element or group');
}
lastElement.quantifier = 'zeroOrOne';
i++;
continue;
}
case '*': {
const lastElement = last(last(stack));
if (!lastElement || lastElement.quantifier !== 'exactlyOne') {
throw new Error('Quantifier must follow an unquantified element or group');
}
lastElement.quantifier = 'zeroOrMore';
i++;
continue;
}
case '+': {
const lastElement = last(last(stack));
if (!lastElement || lastElement.quantifier !== 'exactlyOne') {
throw new Error('Quantifier must follow an unquantified element or group');
}
const zeroOrMoreCopy = { ...lastElement, quantifier: 'zeroOrMore'};
last(stack).push(zeroOrMoreCopy);
i++;
continue;
}
case '(': {
stack.push([]);
i++;
continue;
}
case ')': {
if (stack.length <= 1) {
throw new Error(`No group to close at index ${i}`)
}
const states = stack.pop();
last(stack).push({
type: 'groupElement',
states,
quantifier: 'exactlyOne'
});
i++;
continue;
}
case '\\': {
if (i+1 >= re.length) {
throw new Error(`Bad escape character at index ${i}`);
}
last(stack).push({
type: 'element',
value: re[i+1],
quantifier: 'exactlyOne',
});
i += 2;
continue;
}
default: {
last(stack).push({
type: 'element',
value: next,
quantifier: 'exactlyOne',
});
i++;
continue;
}
}
}
if (stack.length !== 1) {
throw new Error('Unmatched groups in regular expressions');
}
return stack[0];
}
// const {inspect} = require('util');
// const regex = 'a?(b.*c)+d';
// console.log(inspect(parse(regex), false, Infinity));
module.exports = parse;