/
nfa.js
318 lines (257 loc) · 8.2 KB
/
nfa.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/*
Thompson NFA Construction and Search.
*/
/*
A state in Thompson's NFA can either have
- a single symbol transition to a state
or
- up to two epsilon transitions to another states
but not both.
*/
function createState(isEnd) {
return {
isEnd,
transition: {},
epsilonTransitions: []
};
}
function addEpsilonTransition(from, to) {
from.epsilonTransitions.push(to);
}
/*
Thompson's NFA state can have only one transition to another state for a given symbol.
*/
function addTransition(from, to, symbol) {
from.transition[symbol] = to;
}
/*
Construct an NFA that recognizes only the empty string.
*/
function fromEpsilon() {
const start = createState(false);
const end = createState(true);
addEpsilonTransition(start, end);
return { start, end };
}
/*
Construct an NFA that recognizes only a single character string.
*/
function fromSymbol(symbol) {
const start = createState(false);
const end = createState(true);
addTransition(start, end, symbol);
return { start, end };
}
/*
Concatenates two NFAs.
*/
function concat(first, second) {
addEpsilonTransition(first.end, second.start);
first.end.isEnd = false;
return { start: first.start, end: second.end };
}
/*
Unions two NFAs.
*/
function union(first, second) {
const start = createState(false);
addEpsilonTransition(start, first.start);
addEpsilonTransition(start, second.start);
const end = createState(true);
addEpsilonTransition(first.end, end);
first.end.isEnd = false;
addEpsilonTransition(second.end, end);
second.end.isEnd = false;
return { start, end };
}
/*
Apply Closure (Kleene's Star) on an NFA.
*/
function closure(nfa) {
const start = createState(false);
const end = createState(true);
addEpsilonTransition(start, end);
addEpsilonTransition(start, nfa.start);
addEpsilonTransition(nfa.end, end);
addEpsilonTransition(nfa.end, nfa.start);
nfa.end.isEnd = false;
return { start, end };
}
/*
Zero-or-one of an NFA.
*/
function zeroOrOne(nfa) {
const start = createState(false);
const end = createState(true);
addEpsilonTransition(start, end);
addEpsilonTransition(start, nfa.start);
addEpsilonTransition(nfa.end, end);
nfa.end.isEnd = false;
return { start, end };
}
/*
One on more of an NFA.
*/
function oneOrMore(nfa) {
const start = createState(false);
const end = createState(true);
addEpsilonTransition(start, nfa.start);
addEpsilonTransition(nfa.end, end);
addEpsilonTransition(nfa.end, nfa.start);
nfa.end.isEnd = false;
return { start, end };
}
/*
Converts a postfix regular expression into a Thompson NFA.
*/
function toNFA(postfixExp) {
if (postfixExp === '') {
return fromEpsilon();
}
const stack = [];
for (const token of postfixExp) {
if (token === '*') {
stack.push(closure(stack.pop()));
} else if (token === "?") {
stack.push(zeroOrOne(stack.pop()));
} else if (token === "+") {
stack.push(oneOrMore(stack.pop()));
} else if (token === '|') {
const right = stack.pop();
const left = stack.pop();
stack.push(union(left, right));
} else if (token === '.') {
const right = stack.pop();
const left = stack.pop();
stack.push(concat(left, right));
} else {
stack.push(fromSymbol(token));
}
}
return stack.pop();
}
/*
Regex to NFA construction using a parse tree.
*/
const { toParseTree } = require('./parser2');
function toNFAfromParseTree(root) {
if (root.label === 'Expr') {
const term = toNFAfromParseTree(root.children[0]);
if (root.children.length === 3) // Expr -> Term '|' Expr
return union(term, toNFAfromParseTree(root.children[2]));
return term; // Expr -> Term
}
if (root.label === 'Term') {
const factor = toNFAfromParseTree(root.children[0]);
if (root.children.length === 2) // Term -> Factor Term
return concat(factor, toNFAfromParseTree(root.children[1]));
return factor; // Term -> Factor
}
if (root.label === 'Factor') {
const atom = toNFAfromParseTree(root.children[0]);
if (root.children.length === 2) { // Factor -> Atom MetaChar
const meta = root.children[1].label;
if (meta === '*')
return closure(atom);
if (meta === '+')
return oneOrMore(atom);
if (meta === '?')
return zeroOrOne(atom);
}
return atom; // Factor -> Atom
}
if (root.label === 'Atom') {
if (root.children.length === 3) // Atom -> '(' Expr ')'
return toNFAfromParseTree(root.children[1]);
return toNFAfromParseTree(root.children[0]); // Atom -> Char
}
if (root.label === 'Char') {
if (root.children.length === 2) // Char -> '\' AnyChar
return fromSymbol(root.children[1].label);
return fromSymbol(root.children[0].label); // Char -> AnyCharExceptMeta
}
throw new Error('Unrecognized node label ' + root.label);
}
function toNFAFromInfixExp(infixExp) {
if (infixExp === '')
return fromEpsilon();
return toNFAfromParseTree(toParseTree(infixExp));
}
/*
Process a string through an NFA by recurisively (depth-first) traversing all the possible paths until finding a matching one.
The NFA has N states, from each state it can go to at most N possible states, yet there might be at most 2^N possible paths,
therefore, worst case it'll end up going through all of them until it finds a match (or not), resulting in very slow runtimes.
*/
function recursiveBacktrackingSearch(state, visited, input, position) {
if (visited.includes(state)) {
return false;
}
visited.push(state);
if (position === input.length) {
if (state.isEnd) {
return true;
}
if (state.epsilonTransitions.some(s => recursiveBacktrackingSearch(s, visited, input, position))) {
return true;
}
} else {
const nextState = state.transition[input[position]];
if (nextState) {
if (recursiveBacktrackingSearch(nextState, [], input, position + 1)) {
return true;
}
} else {
if (state.epsilonTransitions.some(s => recursiveBacktrackingSearch(s, visited, input, position))) {
return true;
}
}
return false;
}
}
/*
Follows through the epsilon transitions of a state until reaching
a state with a symbol transition which gets added to the set of next states.
*/
function addNextState(state, nextStates, visited) {
if (state.epsilonTransitions.length) {
for (const st of state.epsilonTransitions) {
if (!visited.find(vs => vs === st)) {
visited.push(st);
addNextState(st, nextStates, visited);
}
}
} else {
nextStates.push(state);
}
}
/*
Process a string through an NFA. For each input symbol it transitions into in multiple states at the same time.
The string is matched if after reading the last symbol, is has transitioned into at least one end state.
For an NFA with N states in can be at at most N states at a time. This algorighm finds a match by processing the input word once.
*/
function search(nfa, word) {
let currentStates = [];
/* The initial set of current states is either the start state or
the set of states reachable by epsilon transitions from the start state */
addNextState(nfa.start, currentStates, []);
for (const symbol of word) {
const nextStates = [];
for (const state of currentStates) {
const nextState = state.transition[symbol];
if (nextState) {
addNextState(nextState, nextStates, []);
}
}
currentStates = nextStates;
}
return currentStates.find(s => s.isEnd) ? true : false;
}
function recognize(nfa, word) {
// return recursiveBacktrackingSearch(nfa.start, [], word, 0);
return search(nfa, word);
}
module.exports = {
toNFA,
toNFAFromInfixExp,
recognize
};