-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJ_LexYacc.js
1715 lines (1696 loc) · 53.1 KB
/
J_LexYacc.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function error(str) {
throw str;
}
class StringReader {
constructor(string) {
this.string = string;
this.i = 0;
this.lasti = 0;
}
readCharOne() {
if (this.i < this.string.length) {
var char = this.string.charAt(this.i);
this.i += 1;
return char;
} else {
return null;
}
}
readChar() {
this.lasti = this.i;
var char = this.readCharOne();
if (char == "\\") {
char += this.readCharOne();
}
return char;
}
/**
* 替换字符串中的某一部分
* @param {*} start 包含start
* @param {*} end 不包含end
* @param {*} string 替换字符串
*/
replace(start, end, string) {
var move = 0;
if (this.i >= end) {
move = string.length - (end - start);
this.i += move;
}
this.string =
this.string.substring(0, start) + string + this.string.substring(end);
return move;
}
}
class J_Lex {
static run(lex) {
lex.regxs = Object.create(lex.input.regxs);
this.preprocess(lex);
this.createNFA(lex);
this.createDFA(lex);
this.buildClassTable(lex);
}
static preprocess(lex) {
var regxs = lex.regxs;
var filter = new Map();
//检查是否有重复ID
var m = new Map();
regxs.forEach((v) => {
if (m.has(v.id)) {
error("ID重复:" + v.id);
}
m.set(v.id, v);
});
function brace(element) {
var id = element.id;
var regx = element.regx;
//检查是否有循环定义
if (filter.has(id)) {
if (filter.get(id) == false) {
error("循环定义:" + id);
} else {
return;
}
} else {
filter.set(id, false);
}
var sr = new StringReader(regx);
var char = sr.readChar();
while (char != null) {
//判断是否有循环定义
if (char == "{") {
var start = sr.i - 1;
var temp1 = "";
char = sr.readChar();
while (char != "}") {
if (char == null) {
error("大括号不匹配:" + regx);
}
temp1 += char;
char = sr.readChar();
}
var end = sr.i - 1;
if (m.has(temp1)) {
brace(m.get(temp1));
sr.replace(start, end + 1, "(" + m.get(temp1).regx + ")");
} else {
error("未定义ID:" + temp1);
}
} else if (char == "[") {
var start = sr.i - 1;
//处理中括号
var temp1 = "";
var lastChar = null;
char = sr.readChar();
while (char != "]") {
if (char == null) {
error("中括号不匹配:" + regx);
} else if (char == "-") {
if (lastChar == null) {
error("-前不存在字符:" + regx);
}
char = sr.readChar();
if (char == null) {
error("-后不存在字符:" + regx);
}
var f = lastChar.charCodeAt(0);
var t = char.charCodeAt(0);
if (lastChar.charAt(0) == "\\") {
if (lastChar.length == 1) {
error("\\后不存在字符" + regx);
}
f = lastChar.charCodeAt(1);
}
if (char.charAt(0) == "\\") {
if (char.length == 1) {
error("\\后不存在字符" + regx);
}
t = char.charCodeAt(1);
}
if (f > t) {
var temp2 = f;
f = t;
t = temp2;
}
temp1 +=
"<(c)=\\>c.charCodeAt(0)\\>=" +
f +
"&&c.charCodeAt(0)\\<=" +
t +
">|";
lastChar = null;
char = null;
} else if (
char == "(" ||
char == ")" ||
char == "*" ||
char == "+" ||
char == "|" ||
char == "{" ||
char == "}" ||
char == "[" ||
char == "]" ||
char == "<" ||
char == ">"
) {
error("中括号中出现非法字符" + char + ":" + regx);
} else {
if (lastChar != null) {
temp1 += lastChar + "|";
}
}
lastChar = char;
char = sr.readChar();
}
if (lastChar != null) {
temp1 += lastChar + "|";
}
temp1 = "(" + temp1.substring(0, temp1.length - 1) + ")";
var end = sr.i - 1;
sr.replace(start, end + 1, temp1);
} else if (char == "-") {
error("-出现在[]外:" + regx);
} else if (char == "<") {
var temp1 = "";
char = sr.readChar();
while (char != ">") {
if (char == null) {
error("尖括号不匹配:" + regx);
}
temp1 += char;
char = sr.readChar();
}
} else if (char == "(") {
sr.replace(sr.i, sr.i, "(");
} else if (char == ")") {
sr.replace(sr.i, sr.i, ")");
} else if (char == "|") {
sr.replace(sr.i - 1, sr.i, ")|(");
}
char = sr.readChar();
}
element.regx = "(" + sr.string + ")";
filter.set(id, true);
}
regxs.forEach((element) => {
brace(element);
});
}
static createNFA(lex) {
function NFAAddSide(NFA, v, inNodeID, outNodeID) {
if (v.charAt(0) == "c") {
var inNode = NFA.sides.get(inNodeID);
var vv = v.substring(1);
if (!inNode.has(vv)) {
inNode.set(vv, []);
}
inNode.get(vv).push(outNodeID);
} else if (v.charAt(0) == "f") {
if (!NFA.fsides.has(inNodeID)) {
NFA.fsides.set(inNodeID, new Map());
}
var inNode = NFA.fsides.get(inNodeID);
if (!inNode.has(outNodeID)) {
inNode.set(outNodeID, []);
}
var f = v.substring(1);
inNode.get(outNodeID).push({ f: f, r: eval(f) });
} else {
error("遇到非法符号:" + v.length);
}
}
//v以m开头表示混合,以c开头表示字符,以f开头表示函数
function buildNFA(NFA, v, inNodeID, outNodeID) {
var sr = new StringReader(v);
var char = sr.readChar();
var start = -1;
var end = -1;
//递归边界
if (char == "c") {
if (v.charAt(1) == "\\") {
NFAAddSide(NFA, "c" + v.charAt(2), inNodeID, outNodeID);
} else {
NFAAddSide(NFA, v, inNodeID, outNodeID);
}
return;
} else if (char == "f") {
char = sr.readChar();
while (char != null) {
if (char.charAt(0) == "\\") {
sr.replace(sr.i - 2, sr.i - 1, "");
}
char = sr.readChar();
}
try {
var f = eval(sr.string.substring(1));
if (!(f instanceof Function)) {
error("给予的匹配非函数:" + sr.string.substring(1));
}
} catch (e) {
error("给予的匹配函数非法:" + sr.string.substring(1));
}
NFAAddSide(NFA, sr.string, inNodeID, outNodeID);
return;
}
char = sr.readChar();
var type = "";
if (char == "(") {
start = sr.i;
var layer = 1;
while (true) {
char = sr.readChar();
if (char == null) {
error("小括号不匹配:" + v);
} else if (char == "(") {
layer += 1;
} else if (char == ")") {
layer -= 1;
} else if (char == "<") {
while (char != ">") {
char = sr.readChar();
}
}
if (layer == 0) {
end = sr.i - 2;
type = "m";
break;
}
}
} else if (char == "<") {
start = sr.i;
while (char != ">") {
char = sr.readChar();
}
end = sr.i - 2;
type = "f";
} else if (
char == ")" ||
char == "|" ||
char == "*" ||
char == "+" ||
char == ">"
) {
error("符号非法使用:" + char);
} else {
start = sr.i - 1;
end = sr.i - 1;
type = "c";
}
var string1 = v.substring(start, end + 1);
var char2 = "";
var or = false;
char = sr.readChar();
if (char == "*" || char == "+") {
char2 = char;
char = sr.readChar();
}
if (char == "|") {
or = true;
char = sr.readChar();
}
//是否有OR
if (char != null) {
if (or) {
buildNFA(NFA, "m" + v.substring(sr.lasti), inNodeID, outNodeID);
} else {
var nextID = NFA.nextID;
NFA.nextID += 1;
NFA.sides.set(nextID, new Map());
buildNFA(NFA, "m" + v.substring(sr.lasti), nextID, outNodeID);
outNodeID = nextID;
}
}
if (char2 == "*") {
var nextID = NFA.nextID;
NFA.nextID += 1;
NFA.sides.set(nextID, new Map());
NFAAddSide(NFA, "c", inNodeID, nextID);
NFAAddSide(NFA, "c", nextID, outNodeID);
buildNFA(NFA, type + string1, nextID, nextID);
} else if (char2 == "+") {
var nextID = NFA.nextID;
NFA.nextID += 1;
NFA.sides.set(nextID, new Map());
buildNFA(NFA, type + string1, inNodeID, nextID);
NFAAddSide(NFA, "c", nextID, outNodeID);
buildNFA(NFA, type + string1, nextID, nextID);
} else {
buildNFA(NFA, type + string1, inNodeID, outNodeID);
}
}
var regxs = lex.regxs;
var NFA = {};
lex.NFA = NFA;
NFA.sides = new Map();
NFA.fsides = new Map();
NFA.sides.set(0, new Map());
NFA.nextID = 1;
regxs.forEach((element) => {
if (element.noMatch != true) {
NFA.sides.set(NFA.nextID, new Map());
element.NFAAcceptState = NFA.nextID;
NFA.nextID += 1;
}
});
NFA.lastEndState = NFA.nextID - 1;
regxs.forEach((element) => {
if (element.noMatch != true) {
buildNFA(NFA, "m" + element.regx, 0, element.NFAAcceptState);
}
});
}
static createDFA(lex) {
function SetToString(NumOfID, set) {
var output = "";
for (var i = 0; i < NumOfID; ++i) {
if (set.has(i)) {
output += "1";
} else {
output += "0";
}
}
return output;
}
var NFA = lex.NFA;
var DFA = { nextID: 0 };
lex.DFA = DFA;
DFA.sides = new Map();
var StateMap = new Map();
DFA.StateMap = StateMap;
DFA.States = new Map();
DFA.funcs = new Map();
function buildDFA(NFA, DFA, startSet) {
//空串闭包扩展
var closure = new Set();
function calcuClosure(v) {
if (closure.has(v)) {
return;
}
closure.add(v);
//计算空字符串导致的闭包
var toNodes = NFA.sides.get(v).get("");
if (toNodes != undefined) {
toNodes.forEach((vv) => {
calcuClosure(vv);
});
}
//计算函数导致的闭包
var funcs = NFA.fsides.get(v);
if (funcs != undefined) {
funcs.forEach((v, k) => {
var t = false;
for (var i = 0; i < v.length; ++i) {
if (v[i].r("")) {
t = true;
break;
}
}
if (t == true) {
calcuClosure(k);
}
});
}
}
startSet.forEach((v) => {
calcuClosure(v);
});
//ID分配
var name = SetToString(NFA.nextID, closure);
// console.log(name);
//判断是否为已计算过的状态
if (!StateMap.has(name)) {
StateMap.set(name, DFA.nextID); //记录状态已出现
DFA.sides.set(DFA.nextID, new Map());
var fromId = DFA.nextID;
var endState = new Set(); //计算闭包包含的终结状态
closure.forEach((v) => {
if (v <= NFA.lastEndState && v > 0) {
endState.add(v);
}
});
DFA.States.set(fromId, { endState: endState });
DFA.nextID += 1;
//计算到达集
//计算因字符而导致的状态转换
var CharSet = new Set(); //已检查过的字符
CharSet.add("");
closure.forEach((nodeID) => {
var node = NFA.sides.get(nodeID);
node.forEach((v, k) => {
if (!CharSet.has(k)) {
var char = k; //当前检查的字符
CharSet.add(k);
var startSet2 = new Set();
closure.forEach((nodeID1) => {
//计算因字符匹配到达的节点
var node1 = NFA.sides.get(nodeID1);
if (node1.has(char)) {
var toNodes = node1.get(char);
toNodes.forEach((v1) => {
startSet2.add(v1);
});
}
//计算因函数匹配到达的节点
var funcs = NFA.fsides.get(nodeID1);
if (funcs != undefined) {
funcs.forEach((v, k) => {
var t = false;
for (var i = 0; i < v.length; ++i) {
if (v[i].r(char)) {
t = true;
break;
}
}
if (t == true) {
startSet2.add(k);
}
});
}
});
var toId = buildDFA(NFA, DFA, startSet2);
DFA.sides.get(fromId).set("c" + char, toId);
}
});
});
//计算因函数而导致的状态转换
var map1 = new Map();
closure.forEach((nodeID1) => {
var node1 = NFA.fsides.get(nodeID1);
if (node1 != undefined) {
node1.forEach((v, k) => {
if (!map1.has(k)) {
map1.set(k, []);
}
map1.set(k, map1.get(k).concat(v));
});
}
});
if (map1.size != 0) {
//将函数加入DFA.funcs中
DFA.funcs.set(fromId, Array.from(map1.values()));
//计算转移
var allArray = Array.from(map1.keys());
//作为位指示的array
var bits = "f".repeat(allArray.length - 1);
bits += "t";
var sr = new StringReader(bits);
var stop = false;
while (!stop) {
var startSet3 = new Set();
stop = true;
for (var i = 0; i < sr.string.length; ++i) {
if (sr.string.charAt(i) == "t") {
startSet3.add(allArray[i]);
} else {
stop = false;
}
}
//递归计算DFA
var toId = buildDFA(NFA, DFA, startSet3);
DFA.sides.get(fromId).set("f" + sr.string, toId);
//二进制加以一
for (var i = sr.string.length - 1; i >= 0; --i) {
if (sr.string.charAt(i) == "t") {
sr.replace(i, i + 1, "f");
} else {
sr.replace(i, i + 1, "t");
break;
}
}
}
// console.log(bits);
}
}
return StateMap.get(name);
}
var startSet = new Set();
startSet.add(0);
buildDFA(NFA, DFA, startSet);
}
static buildClassTable(lex) {
var DFA = lex.DFA;
var table = {};
var funcTranTable = {};
var funcsMap = new Map();
var funcs = [];
var ftable = {};
function getFuncsId(funcString) {
if (funcsMap.has(funcString)) {
return funcsMap.get(funcString);
} else {
funcs.push(funcString);
funcsMap.set(funcString, funcs.length - 1);
return funcs.length - 1;
}
}
DFA.sides.forEach((side, nodeId) => {
side.forEach((v, k) => {
if (k.charAt(0) == "c") {
table[k.substring(1) + "_" + nodeId] = v;
} else if (k.charAt(0) == "f") {
funcTranTable[k.substring(1) + "_" + nodeId] = v;
}
});
var node = DFA.funcs.get(nodeId);
if (node != undefined) {
var ft = [];
node.forEach((v) => {
var temp1 = [];
v.forEach((element) => {
temp1.push(getFuncsId(element.f));
});
ft.push(temp1);
});
ftable[nodeId] = ft;
}
});
var code5 = "";
for (var i = 0; i < lex.DFA.nextID; ++i) {
code5 += JSON.stringify(Array.from(lex.DFA.States.get(i).endState)) + ",";
}
var codeToName = {};
lex.input.regxs.forEach((v) => {
if (v.NFAAcceptState != undefined) {
codeToName[v.NFAAcceptState] = v.id;
}
});
var code4 =
`{stateTranTable:` +
JSON.stringify(table) +
`,funcTranTable:` +
JSON.stringify(funcTranTable) +
`,ftable:` +
JSON.stringify(ftable) +
`,funcs:` +
JSON.stringify(funcs) +
`,AccStatID:[` +
code5 +
`],codeToName:` +
JSON.stringify(codeToName) +
`}`;
if (lex.input.code == undefined) {
lex.input.code = {};
}
if (lex.input.code.prefix == undefined) {
lex.input.code.prefix = "";
}
if (lex.input.code.suffix == undefined) {
lex.input.code.suffix = "";
}
var code3 =
lex.input.code.prefix +
`class J_SimpleLexers {
static info = ` +
code4 +
`
static stateTranTableInit() {
if (this.info.stateTranTableInited != true) {
for (var i = 0; i < this.info.funcs.length; ++i) {
this.info.funcs[i] = eval(this.info.funcs[i]);
}
this.info.stateTranTableInited = true;
}
}
constructor() {
this.initState();
J_Lexers.stateTranTableInit();
}
initState() {
this.string = "";
this.state = 0;
}
/**
* 处理一个字符
* @param {*} char 输入字符
*/
readChar(char) {
var next = J_SimpleLexers.info.stateTranTable[char + "_" + this.state];
if (next == undefined) {
var ft = J_SimpleLexers.info.ftable[this.state];
if (ft == undefined) {
return false;
} else {
var string = "";
for (var i = 0; i < ft.length; ++i) {
var temp = ft[i];
var t = false;
for (var j = 0; j < temp.length; ++j) {
if (J_SimpleLexers.info.funcs[temp[j]](char)) {
t = true;
break;
}
}
if (t) {
string += "t";
} else {
string += "f";
}
}
var next = J_SimpleLexers.info.funcTranTable[string + "_" + this.state];
if (next == undefined) {
return false;
} else {
this.state = next;
this.string += char;
return true;
}
}
} else {
this.state = next;
this.string += char;
return true;
}
}
}
class J_Lexers extends J_SimpleLexers {
/**
* 初始化词法分析器状态,每次重新运行前调用
*/
initState() {
super.initState();
this.lastFinal = { state: 0, string: "" };
}
/**
* 实行一次最大匹配,支持流式读取,若inputStr不足以形成一个符号,则返回null,可继续调用readTag(接下来的内容),直到最大匹配并返回匹配到的词法符号
* @param {*} inputStr 内容字符串
* @returns 如果识别到一个词法符号则返回对象var output = {tag:[匹配符号1,匹配符号2...],value:"匹配字符串",restStr:"剩余的字符串"},如果未识别到一个词法符号则返回null。如果匹配非法,则output.error = true
*/
readTag(inputStr) {
var output = {};
for (var i = 0; i < inputStr.length; ++i) {
var b = this.readChar(inputStr.charAt(i));
var stateS = J_Lexers.info.AccStatID[this.state];
if (stateS.length > 0) {
this.lastFinal.state = this.state;
this.lastFinal.string = this.string;
}
if (!b) {
var state = this.lastFinal.state;
var stateS = J_Lexers.info.AccStatID[state];
var stateName = [];
stateS.forEach((v) => {
stateName.push(J_Lexers.info.codeToName[v]);
});
output.tag = stateName;
output.value = this.lastFinal.string;
output.restStr =
this.string.substring(this.lastFinal.string.length) +
inputStr.substring(i);
this.initState();
if (state == 0) {
output.error = true;
}
return output;
}
}
return null;
}
/**
* 内容读取结束后调用,输出最后一次匹配内容,如果无法匹配全部内容 output.error = true
* @returns 同readTag
*/
finishRead() {
var output = {};
var state = this.lastFinal.state;
var stateS = J_Lexers.info.AccStatID[state];
var stateName = [];
stateS.forEach((v) => {
stateName.push(J_Lexers.info.codeToName[v]);
});
output.tag = stateName;
output.value = this.lastFinal.string;
output.restStr = this.string.substring(this.lastFinal.string.length);
this.initState();
if (output.restStr.length > 0) {
output.error = true;
}
return output;
}
}
` +
lex.input.code.suffix;
lex.code = code3;
}
}
class J_Yacc {
static run(yacc) {
this.preprocess(yacc);
// console.log(yacc.formalGram.gramsSettings);
// console.log(yacc.formalGram.P);
this.createClosuer(yacc);
this.createTable(yacc);
// console.log(yacc.formalGram.P);
// console.log(yacc.formalGram.Vn);
// console.log(yacc.formalGram.Vt);
// console.log(yacc.formalGram.closuers);
// console.log(yacc.formalGram.table);
this.buildClass(yacc);
}
static preprocess(yacc) {
var formalGram = yacc.input.formalGram;
var P = formalGram.P;
var Vt = formalGram.Vt;
var S = formalGram.S;
var gramsMap = new Map();
var gramsSettings = new Map();
if (formalGram.asso == undefined) {
formalGram.asso = "m";
}
var globalAsso = formalGram.asso;
P.forEach((element) => {
if (!gramsMap.has(element.id)) {
gramsMap.set(element.id, []);
}
if (!(element.gram instanceof Array)) {
element.gram = [element.gram];
}
if (element.priority == undefined) {
element.priority = [];
} else if (!(element.priority instanceof Array)) {
element.priority = [element.priority];
}
if (element.asso == undefined) {
element.asso = [];
} else if (!(element.asso instanceof Array)) {
element.asso = [element.asso];
}
element.gram.forEach((v) => {
var sr = new StringReader(v + " ");
var char = sr.readChar();
var string = "";
var output = [];
while (char != null) {
if (char == " ") {
// if (string != "") {
output.push(string);
string = "";
// }
} else {
string += char;
}
char = sr.readChar();
}
gramsMap.get(element.id).push(output);
});
});
var Vn = Array.from(gramsMap.keys());
//编号分配
var i = 1;
var Vti = new Map();
//空串分配ID 0
Vti.set("", 0);
Vt.forEach((vt) => {
if (Vti.has(vt)) {
error("非终结符重复定义:" + vt);
}
Vti.set(vt, i);
++i;
});
var Vni = new Map();
Vn.forEach((vn) => {
if (Vti.has(vn)) {
error("非终结符同时也是终结符:" + vn);
}
Vni.set(vn, i);
++i;
});
//做文法的增广
var S_ = S + "'";
while (Vti.has(S_) || Vni.has(S_)) {
S_ += "'";
}
Vni.set(S_, i);
gramsMap.set(S_, [[S]]);
var Pi = new Map();
//“符号ID化”及“符号是否定义检查”
gramsMap.forEach((v, k) => {
v.forEach((element2) => {
for (var j = 0; j < element2.length; ++j) {
var temp1 = element2[j];
var temp2 = Vni.get(temp1);
if (temp2 == undefined) {
temp2 = Vti.get(temp1);
}
if (temp2 == undefined) {
error("未定义的符号:" + temp1);
}
element2[j] = temp2;
}
});
Pi.set(Vni.get(k), v);
});
//计算反向映射表
var Vtn = new Map();
Vti.forEach((v, k) => {
Vtn.set(v, k);
});
var Vnn = new Map();
Vni.forEach((v, k) => {
Vnn.set(v, k);
});
P.forEach((element) => {
var priority = element.priority;
var asso = element.asso;
var settings = [];
if (gramsSettings.has(Vni.get(element.id))) {
settings = gramsSettings.get(Vni.get(element.id));
}
var lastPNud = 0;
var lastANud = 0;
for (var i = 0; i < element.gram.length; ++i) {
var p = priority[i];
var a = asso[i];
if (i >= priority.length) {
p = priority[lastPNud];
} else {
lastPNud = i;
}
if (a == undefined) {
a = asso[lastANud];
if (a == undefined) {
a = globalAsso;
}
} else {
lastANud = i;
}
settings.push({ priority: p, asso: a });
}
gramsSettings.set(Vni.get(element.id), settings);
});
//将拓广后的开始符的优先级和结合性定义好
gramsSettings.set(Vni.get(S_), [
{
priority: formalGram.S_priority,
asso: formalGram.S_asso == undefined ? globalAsso : formalGram.S_asso,
},
]);
yacc.formalGram = {
P: Pi,
Vt: Vti,
Vn: Vni,
Vtn: Vtn,
Vnn: Vnn,
S: S_,
gramsSettings: gramsSettings,
};
}
static __ProjectToString(formalGram, c) {
var P = formalGram.P;
var Vnn = formalGram.Vnn;
var Vtn = formalGram.Vtn;
var gram = P.get(c.f)[c.i];
var output = (Vnn.get(c.f) || Vtn.get(c.f)) + "->";
for (var i = 0; i < c.p; ++i) {
output += (Vnn.get(gram[i]) || Vtn.get(gram[i])) + " ";
}
output += "★ ";
for (var i = c.p; i < gram.length; ++i) {
output += (Vnn.get(gram[i]) || Vtn.get(gram[i])) + " ";
}
output += ",";
c.n.forEach((element) => {
output += (element == -1 ? "#" : Vtn.get(element)) + " | ";
});
return output;
}
static __TableItemToString(formalGram, item) {
var Vnn = formalGram.Vnn;
var output = "转换异常!";
if (item.d == "r") {
output = "r:规约" + item.l + "个符号并产生符号" + Vnn.get(item.s);
} else if (item.d == "j") {
output = "j:移进并转移至状态" + item.t;
}
return output;
}
//显示用函数
static __ClosuerToString(formalGram, closuer) {
var output = "";
closuer.forEach((c) => {
output += this.__ProjectToString(formalGram, c) + "\n";
});
return output;
}
static __ClosuersToString(formalGram, closuers) {
var output = "";
closuers.forEach((c, i) => {
output += "状态" + i + ":\n" + this.__ClosuerToString(formalGram, c);
});
return output;
}
static __tableErrorToString(formalGram, tableError, level = 3) {
var output = "状态:";
if (tableError.solved) {
output += "已解决\n";
output += "解决方案:" + tableError.solution.describe + "\n";
} else {
output += "未解决\n";
}
if (level > 0) {
output += "冲突状态:" + tableError.state + "\n";
output +=
"冲突符号:" + formalGram.indexToSymbol[tableError.symbol] + "\n";
}
if (level > 1) {
output +=
"-------------冲突内容-------------:\n" +
this.__TableItemToString(formalGram, tableError.ConflictTableItem[0]) +
"\n与:\n" +
this.__TableItemToString(formalGram, tableError.ConflictTableItem[1]) +
"\n";
}
if (level > 2) {
output +=
"-------------冲突项目-------------:\n" +
this.__ProjectToString(formalGram, tableError.ConflictProject[0]) +
"\n与\n" +
this.__ProjectToString(formalGram, tableError.ConflictProject[1]) +
"\n";
}
if (level > 3) {
output +=
"-------------冲突项目集-------------:\n" +
this.__ClosuerToString(formalGram, tableError.ConflictProjectSet) +
"\n";
}
return output;
}
/**
* 输出冲突处理方案日志
* @param {*} yacc 运行run函数时的输入
* @param {*} outputHandle 输出日志调用函数,默认为console.log,表示输出到控制台
* @param {*} solvedShowLevel 已解决方案的输出等级,输出等级未1,2,3,4,默认为3
* @param {*} unsolvedShowLevel 未解决方案的输出等级,输出等级未1,2,3,4,默认为4
* @param {*} filter 一个过滤器,过滤一些不想输出的日志
*/
static showConflictResolution(
yacc,
outputHandle = console.log,
solvedShowLevel = 3,