-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathDFASerializer.js
More file actions
69 lines (61 loc) · 2.15 KB
/
DFASerializer.js
File metadata and controls
69 lines (61 loc) · 2.15 KB
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
/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
import arrayToString from "../utils/arrayToString.js";
/**
* A DFA walker that knows how to dump them to serialized strings.
*/
export default class DFASerializer {
constructor(dfa, literalNames, symbolicNames) {
this.dfa = dfa;
this.literalNames = literalNames || [];
this.symbolicNames = symbolicNames || [];
}
toString() {
if(this.dfa.s0 === null) {
return null;
}
let buf = "";
let states = this.dfa.sortedStates();
for(let i=0; i<states.length; i++) {
let s = states[i];
if(s.edges!==null) {
let n = s.edges.length;
for(let j=0;j<n;j++) {
let t = s.edges[j] || null;
if(t!==null && t.stateNumber !== 0x7FFFFFFF) {
buf = buf.concat(this.getStateString(s));
buf = buf.concat("-");
buf = buf.concat(this.getEdgeLabel(j));
buf = buf.concat("->");
buf = buf.concat(this.getStateString(t));
buf = buf.concat('\n');
}
}
}
}
return buf.length===0 ? null : buf;
}
getEdgeLabel(i) {
if (i===0) {
return "EOF";
} else if(this.literalNames !==null || this.symbolicNames!==null) {
return this.literalNames[i-1] || this.symbolicNames[i-1];
} else {
return String.fromCharCode(i-1);
}
}
getStateString(s) {
let baseStateStr = ( s.isAcceptState ? ":" : "") + "s" + s.stateNumber + ( s.requiresFullContext ? "^" : "");
if(s.isAcceptState) {
if (s.predicates !== null) {
return baseStateStr + "=>" + arrayToString(s.predicates);
} else {
return baseStateStr + "=>" + s.prediction.toString();
}
} else {
return baseStateStr;
}
}
}