-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.ts
120 lines (106 loc) · 3.74 KB
/
parser.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
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
110
111
112
113
114
115
116
117
118
119
120
import { OperatorsType, QuantityType, StateDataType } from "./types";
const last = <T>(arr: T[]) => arr[arr.length-1]
function parse(regex: string){
const stack : Array<Array<StateDataType>> = [[]]
let i=0;
while (i<regex.length) {
const next = regex[i];
switch(next){
case '.': {
last(stack).push({
type: OperatorsType.Wildcard,
quantify: QuantityType.ExactlyOne
});
i++;
continue;
}
case '?' : {
const lastState = last(last(stack))
if(!lastState || lastState.quantify !== QuantityType.ExactlyOne){
throw new Error('Invalid regex')
}
lastState.quantify = QuantityType.ZeroOrOne
i++;
continue;
}
case '*' : {
const lastState = last(last(stack))
if(!lastState || lastState.quantify !== QuantityType.ExactlyOne){
throw new Error('Invalid regex')
}
lastState.quantify = QuantityType.ZeroOrMore
i++;
continue;
}
case '+' : {
/**
* This is a bit tricky, because we have to check the state exist one and if possible more, then
* we check the one and add a new state with the same type and quantify ZeroOrMore
*/
const lastState = last(last(stack))
if(!lastState || lastState.quantify !== QuantityType.ExactlyOne){
throw new Error('Invalid regex')
}
const zeroOrMoreCopy = {...lastState, quantify: QuantityType.ZeroOrMore}
last(stack).push(zeroOrMoreCopy)
i++;
continue;
}
case '(' : {
/**
* We push a new array to the stack, this will be the new group of state to be added
*/
stack.push([])
i++;
continue;
}
case ')' : {
/**
* After we close the group, we have to check if the group must have at least one element
* then we add the group as a new state to the last state in the stack
*/
const lastState = last(stack)
if(lastState.length <= 1){
throw new Error('Invalid regex')
}
const states = stack.pop()
last(stack).push({
type: OperatorsType.GroupElement,
quantify: QuantityType.ExactlyOne,
states
})
i++;
continue;
}
case '\\' : {
if(i+1 >= regex.length){
throw new Error('Invalid regex')
}
last(stack).push({
type: regex[i+1],
quantify: QuantityType.ExactlyOne,
value: regex[i+1],
});
i+=2;
continue;
}
default: {
last(stack).push({
type: OperatorsType.Element,
quantify: QuantityType.ExactlyOne,
value: next,
});
i++;
continue;
}
}
}
if(stack.length !== 1){
throw new Error('Invalid regex')
}
return stack[0]
}
// import {inspect} from 'util'
// const regex = 'a?(b.*c)+d';
// console.log(inspect(parse(regex),false, Infinity));
export default parse