/
hunter.py
executable file
·1217 lines (1182 loc) · 36.1 KB
/
hunter.py
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
#!/Library/Frameworks/Python.framework/Versions/3.1/bin/python3
# -*- coding: utf-8 -*-
import os, sys
import xml.etree.ElementTree as ET
sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python')
import BGF3
from functools import reduce
debug = False
config = {}
masked = {}
always_terminals = []
always_nonterminals = []
ignore_tokens = []
ignore_lines = []
special = \
[
'DEFINING-SYMBOL',
'DEFINITION-SEPARATOR-SYMBOL',
'START-TERMINAL-SYMBOL',
'END-TERMINAL-SYMBOL',
'START-NONTERMINAL-SYMBOL',
'END-NONTERMINAL-SYMBOL',
'START-GROUP-SYMBOL',
'END-GROUP-SYMBOL',
'START-OPTION-SYMBOL',
'END-OPTION-SYMBOL',
'START-REPETITION-STAR-SYMBOL',
'END-REPETITION-STAR-SYMBOL',
'START-REPETITION-PLUS-SYMBOL',
'END-REPETITION-PLUS-SYMBOL',
'START-SEPLIST-STAR-SYMBOL',
'END-SEPLIST-STAR-SYMBOL',
'START-SEPLIST-PLUS-SYMBOL',
'END-SEPLIST-PLUS-SYMBOL',
'POSTFIX-OPTIONALITY-SYMBOL',
'POSTFIX-REPETITION-STAR-SYMBOL',
'POSTFIX-REPETITION-PLUS-SYMBOL',
'UNDEFINED-NONTERMINALS-ARE-TERMINALS',
'NONTERMINAL-IF-CONTAINS',
'NONTERMINAL-IF-UPPERCASE',
'TERMINAL-IF-UPPERCASE',
'IGNORE-EXTRA-NEWLINES',
'GLUE-NONALPHANUMERIC-TERMINALS'
]
def isAlpha(x):
return reduce(lambda a,b:a and (b=='_' or b=='-' or b.isalnum()),x,True)
def isQNumber(x):
if x =='.':
return False
else:
return reduce(lambda a,b:a and (b=='.' or b.isdigit()),x,True)
def removeComments(ts,s,e):
while s in ts:
i = ts.index(s)
# special case
if i>1 and 'start-terminal-symbol' in config.keys() and ts[i-1:i+2]==[config['start-terminal-symbol'],s,config['end-terminal-symbol']]:
print('STEP 0: adjusted for the comment starting symbol being used as a terminal.')
nts = ts[:i-1]
nts.append(ts[i-1]+ts[i]+ts[i+1])
nts.extend(ts[i+2:])
ts = nts
continue
j = endOfContext(ts,i,e)
if j<0:
print('STEP 0 error: mismatched comment delimiters.')
j = i
nts = ts[:i]
nts.extend(ts[j:])
#print('<<<',ts)
ts = nts
#print('>>>',ts)
return ts
def splitTokenStream(s):
ts = [s[0]]
i = 1
alpha = isAlpha(s[0])
inQuotes = False
while (i<len(s)):
if 'start-terminal-symbol' in config.keys() and 'end-terminal-symbol' in config.keys():
if not inQuotes and s[i] == config['start-terminal-symbol']:
ts.append(s[i])
inQuotes = True
i += 1
continue
elif inQuotes:
if s[i] == config['end-terminal-symbol']:
inQuotes = False
ts[-1] += s[i]
i += 1
continue
if alpha:
if isAlpha(s[i]):
ts[-1] += s[i]
else:
alpha = False
ts.append(s[i])
else:
ts.append(s[i])
alpha = isAlpha(s[i])
i += 1
if 'tabulation-symbol' in config.keys():
ts = mapglue(ts,config['tabulation-symbol'])
return ['\t' if t=='TABULATION' else t for t in filter(lambda x:x not in [' ',' ',' '],['TABULATION' if t == config['tabulation-symbol'] else t for t in ts])]
return list(filter(lambda x:x not in [' ',' ',' '],ts))
# not space, not hard space, not tab; newlines are preserved for now
def reconsiderSpaces(ts,sep,vs):
nts = [ts[0]]
vs = list(vs)
vs.append('\n')
for x in ts[1:]:
if x in ignore_tokens:
continue
if x == sep:
nts.append('')
elif nts[-1] in vs or x in vs:
if nts[-1]=='':
nts[-1] = x
else:
nts.append(x)
else:
nts[-1] += ' ' + x
return nts
def readConfig(f):
global debug
cfg = ET.parse(f)
for e in cfg.findall('*'):
if e.tag == 'mask':
masked[e.findtext('token')] = e.findtext('terminal')
elif e.text:
config[e.tag] = e.text.replace('\\n','\n')
else:
config[e.tag] = ''
if e.tag in ('nonterminal-if-camelcase','nonterminal-if-uppercase','decompose-symbols'):
config[e.tag] = ''
for x in e.findall('except'):
always_terminals.append(x.text)
if e.tag in ('terminal-if-camelcase','terminal-if-uppercase','undefined-nonterminals-are-terminals'):
config[e.tag] = ''
for x in e.findall('except'):
always_nonterminals.append(x.text)
if e.tag=='ignore':
config[e.tag] = ''
for x in e.findall('*'):
if x.tag == 'newline':
ignore_tokens.append('\n')
ignore_tokens.append('@@@0-0')
elif x.tag == 'lines-containing':
ignore_lines.append(x.text)
elif x.tag == 'same-indentation':
ignore_tokens.append('@@@1-1')
else:
ignore_tokens.append(x.text)
if debug:
print('Ok',config)
# bucket sort
def calculateFrequencies(arr):
fs = {}
for x in arr:
if x not in fs.keys():
fs[x] = 1
else:
fs[x] += 1
return fs
def bestFrequency(fs):
bestv = max(fs.values())
for x in fs.keys():
if fs[x] == bestv:
bestk = x
break
return bestk,bestv
# Use terminator symbol to distinguish productions
def useTerminatorSymbol(ts,t):
ps = [[]]
for x in ts:
if x == t:
ps.append([])
else:
ps[-1].append(x)
#ps = list(filter(lambda x:x!=[],ps))
if 'start-label-symbol' in config.keys() or 'end-label-symbol' in config.keys():
print('STEP 4: guessing defining-symbol in a grammar with labels not implemented yet!')
return None,None
dss = list(map(lambda x:'' if len(x)<2 else x[1],filter(lambda x:x!=[],ps)))
bestds,bestdsvalue = bestFrequency(calculateFrequencies(filter(lambda x:x!='',dss)))
prob = bestdsvalue * 100.0 / len(dss)
return prob,bestds
# Use defining symbol to distinguish productions
def useDefiningSymbol(ts,d):
poss = []
prods = []
for i in range(0,len(ts)):
if ts[i] == d and isAlpha(ts[i-1]):
poss.append(i)
poss.append(len(ts)+1)
for i in range(0,len(poss)-1):
if 'end-label-symbol' in config.keys():
if ts[poss[i]-2] == config['end-label-symbol']:
if 'start-label-symbol' in config.keys():
# todo: now works only with one-token labels!
if ts[poss[i]-4] == config['start-label-symbol']:
# everything is fine
p = [ts[poss[i]-3],ts[poss[i]-1]]
else:
print('STEP 4 problem: start-label-symbol mismatch!')
# todo: recover
else:
# no starting symbol for the label
p = [ts[poss[i]-3],ts[poss[i]-1]]
else:
# no label this time
p = ['',ts[poss[i]-1]]
else:
# no labels at all
p = ['',ts[poss[i]-1]]
end = poss[i+1]-1
if 'end-label-symbol' in config.keys() and ts[end-1] == config['end-label-symbol']:
end -= 2
if 'start-label-symbol' in config.keys() and ts[end-1] == config['start-label-symbol']:
end -= 1
p.extend(ts[poss[i]+1:end])
prods.append(p)
return prods
def useDefinitionSeparatorSymbol(ts,d):
poss = [-1]
alts = []
levels = [0,0,0]
for i in range(0,len(ts)):
if 'start-group-symbol' in config.keys() and ts[i]==config['start-group-symbol']:
levels[0] += 1
if 'end-group-symbol' in config.keys() and ts[i]==config['end-group-symbol']:
levels[0] -= 1
if 'start-repeat-symbol' in config.keys() and ts[i]==config['start-repeat-symbol']:
levels[1] += 1
if 'end-repeat-symbol' in config.keys() and ts[i]==config['end-repeat-symbol']:
levels[1] -= 1
if 'start-option-symbol' in config.keys() and ts[i]==config['start-option-symbol']:
levels[2] += 1
if 'end-option-symbol' in config.keys() and ts[i]==config['end-option-symbol']:
levels[2] -= 1
if ts[i] == d:
if levels == [0,0,0]:
poss.append(i)
else:
ts[i] = 'DEFINITION-SEPARATOR-SYMBOL'
poss.append(len(ts)+1)
for i in range(0,len(poss)-1):
alts.append(ts[poss[i]+1:poss[i+1]])
return alts
def findMostProbableTail(ps):
# bucket sort
ss = calculateFrequencies(map(lambda x:x[-1],ps))
# at least 80% has the same end symbol?
# TODO: describe the heuristic
vs = list(ss.values())
m = max(vs)
vs.remove(m)
m2 = max(vs)
#print('m=',m,'m2=',m2,'len(ps)=',len(ps))
if m < max(0.25*len(ps),2*m2):
possibles = []
for i in ss.keys():
if ss[i]>1:
possibles.append((i,ss[i]))
print('Candidates were:',possibles,'with total',len(ps))
return None,None,None
for k in ss.keys():
if ss[k] == m:
break
n2f = []
fps = []
cx = 0
for p in ps:
if p[-1] == k:
fps.append(p)
else:
n2f.append(cx)
cx += 1
return n2f,findCommonTail(fps),100*m/len(ps)
def findCommonTail(ps):
tail = []
for i in range(1,len(ps[0])):
if [x[-i] for x in ps] == [ps[0][-i]]*len(ps):
tail.append(ps[0][-i])
else:
break
tail.reverse()
return tail
def assembleBracketedSymbols(ts,start,end,preserveSpace):
tss = []
inside = False
i = 0
while (i<len(ts)):
if inside:
if preserveSpace and ts[i] != end and tss[-1][-1] != start:
tss[-1] += ' '
tss[-1] += ts[i]
if ts[i] == end:
inside = False
else:
tss.append(ts[i])
if ts[i] == start:
inside = True
i += 1
return tss
def findGroups(ats,start,end):
global debug
poss = [[],[]]
i = j = level = 0
lp = {}
for i in range(0,len(ats)):
for j in range(0,len(ats[i])):
if ats[i][j] == start:
poss[0].append((i,j))
poss[1].append(None)
lp[level] = len(poss[0])-1
level += 1
if ats[i][j] == end:
level -= 1
poss[1][lp.pop(level)] = (i,j)
if len(poss[0]) != len(poss[1]):
print('STEP 8 deadlock: number of start-group-symbol and end-group-symbol occurrences do not match.')
return ats
if debug and poss[0]:
print('poss >>>>>',poss)
print('ats >>>>>>',ats)
for i in range(0,len(poss[0])):
if poss[0][i][0] == poss[1][i][0]:
# same alternative
tmp = ats[poss[0][i][0]][:poss[0][i][1]]
tmp.append([ats[poss[0][i][0]][poss[0][i][1]:poss[1][i][1]][1:]])
tmp.extend(ats[poss[0][i][0]][poss[1][i][1]+1:])
ats[poss[0][i][0]] = tmp
#print '-->',tmp
else:
newats = []
for j in range(0,len(ats)):
if j<poss[0][i][0]:
newats.append(ats[j])
elif j>poss[1][i][0]:
newats.append(ats[j])
elif j==poss[0][i][0]:
before = ats[j][:poss[0][i][1]]
tmp = [ats[j][poss[0][i][1]+1:]]
elif j==poss[1][i][0]:
tmp.append(ats[j][:poss[1][i][1]])
before.append(tmp)
before.extend(ats[j][poss[1][i][1]+1:])
newats.append(before)
else:
tmp.append(ats[j])
ats = newats
#print '--> not implemented yet'
if len(ats) == 1 and len(ats[0]) == 1 and type(ats[0][0]) == type([]):
ats = ats[0][0]
return ats
def findSpecialGroups(ats,start,end):
global debug
poss = [[],[]]
i = j = level = 0
lp = {}
for i in range(0,len(ats)):
for j in range(0,len(ats[i])):
if ats[i][j] == start:
poss[0].append((i,j))
poss[1].append(None)
lp[level] = len(poss[0])-1
level += 1
if ats[i][j] == end:
level -= 1
poss[1][lp.pop(level)] = (i,j)
if len(poss[0]) != len(poss[1]):
print('STEP 8 deadlock: number of start-?-symbol and end-?-symbol occurrences do not match.')
return ats
if debug and poss[0]:
print('poss >>>>>',poss)
print('ats >>>>>>',ats)
for i in range(0,len(poss[0])):
if poss[0][i][0] != poss[1][i][0]:
newats = []
for j in range(0,len(ats)):
if j<poss[0][i][0]:
newats.append(ats[j])
elif j>poss[1][i][0]:
newats.append(ats[j])
elif j==poss[0][i][0]:
before = ats[j][:poss[0][i][1]+1]
tmp = [ats[j][poss[0][i][1]+1:]]
elif j==poss[1][i][0]:
tmp.append(ats[j][:poss[1][i][1]])
before.append(tmp)
before.extend(ats[j][poss[1][i][1]:])
newats.append(before)
else:
tmp.append(ats[j])
ats = newats
if len(ats) == 1 and len(ats[0]) == 1 and type(ats[0][0]) == type([]):
ats = ats[0][0]
return ats
def mapsymbols(ts,symbol,special):
for i in range(0,len(ts)):
if ts[i] == symbol:
ts[i] = special
elif type(ts[i]) == type([]):
ts[i] = mapsymbols(ts[i],symbol,special)
return ts
def endOfContext(a,i,e):
s = a[i]
level = 1
j = i+1
#print('Searching in a context of',a[i:],'for',e)
while level>0 and j<len(a):
if a[j]==s:
level += 1
elif a[j]==e:
level -= 1
j += 1
if level != 0:
#print('Cannot find end of context in:',a[i:],'@',level)
return -level
return j
def startOfContext(a,i,s):
e = a[i]
level = 1
j = i-1
#print('Searching in a context of',a[i:],'for',e)
while level>0 and j>=0:
if a[j]==s:
level += 1
elif a[j]==e:
level -= 1
j -= 1
if level != 0:
#print('Cannot find end of context in:',a[i:],'@',level)
return -level
return j
def map2expr(ss):
#global debug
debug = False
ess = []
es = []
i = 0
while i<len(ss):
if ss[i] == 'START-REPETITION-STAR-SYMBOL':
j = endOfContext(ss,i,'END-REPETITION-STAR-SYMBOL')
if j<0:
print('Unbalanced bracketing, please fix first. Level:',-j)
j = len(ss)
if debug:
print('>>>context>>>',ss[i:j])
e = BGF3.Star()
e.setExpr(map2expr(ss[i+1:j-1]))
es.append(e)
i = j
elif ss[i] == 'START-REPETITION-PLUS-SYMBOL':
j = endOfContext(ss,i,'END-REPETITION-PLUS-SYMBOL')
if j<0:
print('Unbalanced bracketing, please fix first. Level:',-j)
j = len(ss)
if debug:
print('>>>context>>>',ss[i:j])
e = BGF3.Plus()
e.setExpr(map2expr(ss[i+1:j-1]))
es.append(e)
i = j
elif ss[i] == 'START-OPTION-SYMBOL':
j = endOfContext(ss,i,'END-OPTION-SYMBOL')
if j<0:
print('Unbalanced bracketing, please fix first. Level:',-j)
j = len(ss)
if debug:
print('>>>context>>>',ss[i:j])
e = BGF3.Optional()
e.setExpr(map2expr(ss[i+1:j-1]))
es.append(e)
i = j
elif ss[i] == 'START-SEPLIST-STAR-SYMBOL':
j = endOfContext(ss,i,'END-SEPLIST-STAR-SYMBOL')
if j<0:
print('Unbalanced bracketing, please fix first. Level:',-j)
j = len(ss)
if j-i != 4:
print('Incorrect separator list!')
if debug:
print('>>>context>>>',ss[i:j])
# {x y}* => (x (yx)*)?
e = BGF3.Sequence()
x = map2expr([ss[i+1]])
y = map2expr([ss[i+2]])
e.add(x)
e2 = BGF3.Sequence()
e2.add(y)
e2.add(x)
s = BGF3.Star()
s.setExpr(BGF3.Expression(e2))
e.add(BGF3.Expression(s))
e2 = BGF3.Optional()
e2.setExpr(e)
es.append(e2)
i = j
elif ss[i] == 'START-SEPLIST-PLUS-SYMBOL':
j = endOfContext(ss,i,'END-SEPLIST-PLUS-SYMBOL')
if j<0:
print('Unbalanced bracketing, please fix first.')
j = len(ss)
if j-i != 4:
print('Incorrect separator list!')
if debug:
print('>>>context>>>',ss[i:j])
# {x y}+ => (x (yx)*)
e = BGF3.Sequence()
x = map2expr([ss[i+1]])
y = map2expr([ss[i+2]])
e.add(x)
e2 = BGF3.Sequence()
e2.add(y)
e2.add(x)
s = BGF3.Star()
s.setExpr(BGF3.Expression(e2))
e.add(BGF3.Expression(s))
es.append(e)
i = j
elif ss[i] == 'START-GROUP-SYMBOL':
j = endOfContext(ss,i,'END-GROUP-SYMBOL')
if j<0:
print('Unbalanced bracketing, please fix first.')
j = len(ss)
if i == 0 and j == len(ss):
ss = ss[1:-1]
continue
if debug:
print('>>>context>>>',ss[i:j])
es.append(map2expr(ss[i+1:j-1]))
i = j
elif ss[i] == 'DEFINITION-SEPARATOR-SYMBOL':
if debug:
print('It is a bar! It is a choice!')
ess.append(es)
es = []
i += 1
elif ss[i][0] == config['start-terminal-symbol']:
if debug:
print('TERMINAL',ss[i][1:-1])
e = BGF3.Terminal()
if ss[i][1:-1] == '':
print('Serialisation error: empty terminal, replaced with ""!')
e.setName('""')
else:
e.setName(ss[i][1:-1])
es.append(e)
i += 1
else:
if debug:
print('NONTERMINAL',ss[i])
e = BGF3.Nonterminal()
n = ss[i]
if 'start-nonterminal-symbol' in config.keys() or 'end-nonterminal-symbol' in config.keys():
if n[:len(config['start-nonterminal-symbol'])] == config['start-nonterminal-symbol']:
n = n[len(config['start-nonterminal-symbol']):]
if n[-len(config['end-nonterminal-symbol']):] == config['end-nonterminal-symbol']:
n = n[:-len(config['end-nonterminal-symbol'])]
e.setName(n)
es.append(e)
i += 1
ess.append(es)
if len(ess) == 0:
print('Serialisation error: empty output sequence!')
return
elif len(ess) == 1:
if len(ess[0]) == 0:
print('Serialisation warning: empty internal output sequence, treating like epsilon!')
return BGF3.Expression(BGF3.Epsilon())
elif len(ess[0]) == 1:
return BGF3.Expression(ess[0][0])
else:
e = BGF3.Sequence()
for x in ess[0]:
e.add(BGF3.Expression(x))
return BGF3.Expression(e)
else:
e = BGF3.Choice()
for es in ess:
if len(es) == 0:
print('Serialisation warning: empty internal output sequence, treating like epsilon!')
return BGF3.Expression(BGF3.Epsilon())
elif len(es) == 1:
e.add(BGF3.Expression(es[0]))
else:
ee = BGF3.Sequence()
for x in es:
ee.add(BGF3.Expression(x))
e.add(BGF3.Expression(ee))
return BGF3.Expression(e)
print('Dead code reached!')
return
def mapglue(b,s):
a = b[:]
i = 0
while i < len(a):
if a[i][0] != s[0]:
# first char mismatch
i += 1
continue
combined = a[i]
j = i+1
while j<len(a) and len(combined)<len(s):
combined += a[j]
j += 1
if combined == s:
# success
b = a[:i]
b.append(''.join(a[i:j]))
b.extend(a[j:])
#i = j
i += 1
a = b
else:
# fail
i += 1
return a
def filterNewlines(s):
i = 0
while i<len(s):
if type(s[i])==type([]):
s[i] = filterNewlines(s[i])
i += 1
elif s[i]=='\n':
z = s[:i]
z.extend(s[i+1:])
s = z
else:
i += 1
return s
def glueTerminals(p):
q = []
for y in p[2:]:
if y[0] != config['start-terminal-symbol'] or len(q) == 0 or q[-1][0] != config['start-terminal-symbol']:
q.append(y)
continue
x = y[1:-1]
if len(q)>0 and not isAlpha(q[-1][1:-1]) and not isAlpha(x):
# addition on terminals
q[-1] = q[-1][:-1] + y[1:]
else:
q.append(y)
r = p[:2]
r.extend(q)
if debug and p != r:
print('>>>in>>>>',p)
print('>>>out>>>',r)
return r
def assembleQualifiedNumbers(ts):
ds = []
for x in ts:
if len(ds)>0 and (isQNumber(x) or x=='.') and isQNumber(ds[-1]):
ds[-1] += x
else:
ds.append(x)
return ds
def splitString(s,kw,defd):
# split s according to any kws while preserving them
if len(kw)==0:
return [s]
elif s in defd:
return [s]
elif s.find(kw[0])<0:
return splitString(s,kw[1:],defd)
else:
ss = s.split(kw[0])
done = []
for x in ss:
done.append(x)
done.append(kw[0])
done.pop()
if done[-1]=='':
done.pop()
if done[0] =='':
done = done[1:]
res = []
for a in done:
res.extend(splitString(a,kw[1:],defd))
reject = False
if min(map(len,res))<2:
reject = True
if 'nonterminal-if-contains' in config.keys():
for y in res:
if y in defd or y.find(config['nonterminal-if-contains']) < 0:
continue
else:
reject = True
#print('!!!!! Have to reject',res,'of',s)
#print(kw)
if reject:
return splitString(s,kw[1:],defd)
else:
return res
def decomposeSymbols(p,defd):
# [label, nt, ...]
q = p[:2]
# nested-name-specifiertemplateopt
for x in p[2:]:
match = False
# expanded for better readability
if x in defd:
# defined nonterminal
q.append(x)
continue
if x in always_terminals:
# configured exception
q.append(x)
continue
if x[0] == config['start-terminal-symbol'] and x[-1] == config['end-terminal-symbol']:
# terminal
q.append(x)
continue
#if 'nonterminal-if-contains' in config.keys() and x.find(config['nonterminal-if-contains']) > -1:
# # we have a way of telling nonterminals from terminals, and this is not it
# q.append(x)
# continue
# none of the above: it is a nonterminal, it's not defined and we have no way to dismiss it
var = splitString(x,defd,defd)
#print(var)
if len(var)==1:
q.append(x)
continue
#print(x,'-->',var)
pos = True
# TODO: inspection! strange dead code follows
#for y in var:
# if y in defd:
# # or ('nonterminal-if-contains' in config.keys() and y.find(config['nonterminal-if-contains']) > -1):
# continue
# else:
# pos = False
if pos:
print('STEP 8:',x,'matches as',var)
q.extend(var)
# todo: need to be adjusted if the order of phases is changed
#q.append(config['start-terminal-symbol']+t+config['end-terminal-symbol'])
match = True
continue
if not match:
q.append(x)
return q
def convert2terminal(x,defd):
# unfolded for better readability
if x =='' or x=='\n':
# probably an error, let's not deal with it here
return x
if x in defd:
# defined nonterminal
return x
if x in special:
# pseudo-meta-symbol
return x
if x in always_nonterminals:
# configured exception
return x
if 'nonterminal-if-contains' in config.keys() and x.find(config['nonterminal-if-contains'])>-1:
# undefined nonterminal, but banned by configuration from being converted to a terminal
return x
if 'nonterminal-if-uppercase' in config.keys() and len(x)>1 and x.isupper():
# configuration claims that LONGUPPERCASE is a nonterminal
return x
if 'nonterminal-if-camelcase' in config.keys() and len(x)>1 and x[0].isupper() and x[1:].isalpha() and x not in always_terminals:
# configuration claims that CamelCase is a nonterminal
return x
if x[0] == config['start-terminal-symbol'] and x[-1] == config['end-terminal-symbol']:
# already a terminal
return x
# none of the above
return config['start-terminal-symbol']+x+config['end-terminal-symbol']
def balanceProd(p):
i = 2
while i<len(p):
if p[i].find('START')<0:
i += 1
continue
j = endOfContext(p,i,p[i].replace('START','END'))
if j<0:
# endeavour 1: maybe there is another metasymbol with the same concrete representation?
amb = []
for k in config.keys():
if config[k] == config[p[i].lower()] and k != p[i].lower():
amb.append(k.upper())
oldpi = p[i]
fail = False
for a in amb:
p[i] = a
j = endOfContext(p,i,p[i].replace('START','END'))
if j>0:
break
else:
fail = True
if fail:
print('STEP 7: Cannot balance a production, reverting',oldpi,'to a terminal.')
p[i] = config['start-terminal-symbol']+config[oldpi.lower()]+config['end-terminal-symbol']
i += 1
elif p[i] == oldpi:
print('STEP 7: Problem at',oldpi,'in',p)
i += 1
else:
print('STEP 7: Rebalanced ambiguity of',oldpi,'with',p[i])
i = j
else:
i = j
return p
def postfix2confix(p):
for s in ('POSTFIX-REPETITION-PLUS-SYMBOL','POSTFIX-REPETITION-STAR-SYMBOL','POSTFIX-OPTIONALITY-SYMBOL'):
while s in p:
w = p.index(s)
if w == 0:
print('STEP 7: Impossible place for postfix operator, converted to a terminal.')
p[w] = config['start-terminal-symbol']+p[w]+config['end-terminal-symbol']
continue
if 'end-group-symbol' in config.keys() and p[w-1] == config['end-group-symbol']:
# group
j = startOfContext(p,w-1,config['start-group-symbol'])
if j<0:
print('STEP 7: Impossible to balance the group preceding a postfix operator, converted it to a terminal')
p[w] = config['start-terminal-symbol']+p[w]+config['end-terminal-symbol']
continue
else:
print('STEP 7: Converted postfix metasymbol to confix notation.')
p[w-1] = s.replace('POSTFIX','END')
p[j] = s.replace('POSTFIX','START')
q = p[:w]
q.extend(p[w+1:])
p = q
else:
# single element
print('STEP 7: Converted postfix metasymbol to confix notation.')
q = p[:w-1]
q.append(s.replace('POSTFIX','START'))
q.append(p[w-1])
q.append(s.replace('POSTFIX','END'))
q.extend(p[w+1:])
p = q
return p
def useTerminatorToFixProds(ps,ts):
# TODO: will not work with labels
nps = []
for p in ps:
if ts not in p:
print('STEP 4 warning: a production is disregarded due to the lack of terminator symbol:',p)
while ts in p:
i = p.index(ts)
nps.append(p[:i])
np = [nps[-1][0]]
if config['defining-symbol'] not in p[i+1:]:
tail = p[i+1:]
for x in ignore_tokens:
while x in tail:
tail.remove(x)
if len(tail)>0:
print('STEP 4 problem: terminator symbol without proper defining symbol context.',tail)
return nps
else:
p = tail
continue
else:
nt = p[i+1:p.index(config['defining-symbol'])]
for x in ignore_tokens:
while x in nt:
nt.remove(x)
if len(nt) != 1:
print('STEP 4 problem: cannot determine nonterminal name from',nt)
nt = ' '.join(nt)
else:
nt = nt[0]
np.append(nt)
np.extend(p[p.index(config['defining-symbol'])+1:])
#print('!!!<<<p<<<',p)
p = np
#print('!!!>>>p>>>',p)
return nps
def considerIndentation(ts):
nts = ['@@@0-']
oldlevel = level = 0
# ['A', '\n', '\t', 'B', '\n', '\t', 'C', 'D', 'E', 'F', '\n', '\t', '\t', 'G', '\n', '\t', 'H', '\n', 'X', '\n', '\t', 'Y', '\n', '\t', 'Z', '\n', 'B', '\n', '\t', 'K', '\n', 'C', '\n', '\t', 'L', '\n']
for t in ts:
if t == '\n':
if nts[-1][:3] == '@@@':
nts[-1] += '0'
oldlevel = level
nts.append('@@@'+str(oldlevel)+'-')
level = 0
elif t == '\t':
level += 1
elif nts[-1][:3]=='@@@':
nts[-1] += str(level)
oldlevel = level
nts.append(t)
else:
nts.append(t)
if nts[-1][:3] == '@@@':
nts[-1] += '0'
return nts
if __name__ == "__main__":
if len(sys.argv) != 4:
print('Usage:')
print(' extract.py input.txt config.edd output.bgf')
sys.exit(-1)
readConfig(sys.argv[2])
f = open(sys.argv[1],'r')
# STEP 0: read the file, remove whitespace (?)
print('STEP 0: reading the input file.')
lines = f.readlines()
f.close()
# STEP 1: assemble terminal symbols
#print(ignore_lines)
for sign in ignore_lines:
lines = list(filter(lambda x:x.find(sign)<0,lines))
tokens = list(''.join(lines))
if debug:
print('Token stream:',tokens)
print('STEP 1: removing whitespace and comments, assembling terminal symbols.')
for k in masked.keys():
if len(k)>1 and k.find('@@@')<0:
print('STEP 1: going to glue tokens that resemble masked terminal', k.replace('\n','\\n'))
tokens = mapglue(tokens,k)
if debug:
print('Token stream:',tokens)
tokens = splitTokenStream(tokens)
if 'start-comment-symbol' in config.keys() and 'end-comment-symbol' in config.keys():
# remove comments
# assumption: comments are never nested!
tokens = removeComments(mapglue(mapglue(tokens,config['start-comment-symbol']),config['end-comment-symbol']),config['start-comment-symbol'],config['end-comment-symbol'])
if debug:
print('Token stream:',tokens)
if 'start-terminal-symbol' in config.keys() and 'end-terminal-symbol' in config.keys():
tokens = [config['start-terminal-symbol']+masked[x]+config['end-terminal-symbol'] if x in masked.keys() else x for x in tokens]
tokens = assembleBracketedSymbols(tokens,config['start-terminal-symbol'],config['end-terminal-symbol'],False)
else:
print('STEP 1 was of limited use, sorry: start-terminal-symbol and end-terminal-symbol are not both specified.')
# technically we still need them to denote terminals in our internal representation
config['start-terminal-symbol'] = config['end-terminal-symbol'] = '"'
tokens = [config['start-terminal-symbol']+masked[x]+config['end-terminal-symbol'] if x in masked.keys() else x for x in tokens]
if 'terminal-if-uppercase' in config.keys():
print('STEP 1: all uppercase tokens are considered terminals.')
tokens = [config['start-terminal-symbol']+x+config['end-terminal-symbol']
if len(x)>1
and x[0]!=config['start-terminal-symbol']
and x.isupper()
and x not in always_nonterminals
else x
for x in tokens]
tokens = [config['start-terminal-symbol']+x+config['end-terminal-symbol']
if x==config['start-terminal-symbol']+config['end-terminal-symbol']
or x==config['start-terminal-symbol']
else x
for x in tokens]
if debug:
print('Token stream:',tokens)
# STEP 2: assemble nonterminal symbols
print('STEP 2: assembling nonterminal symbols.')
if 'start-nonterminal-symbol' in config.keys() and 'end-nonterminal-symbol' in config.keys():
tokens = assembleBracketedSymbols(tokens,config['start-nonterminal-symbol'],config['end-nonterminal-symbol'],True)
else:
print('STEP 2 skipped, sorry: start-nonterminal-symbol and end-nonterminal-symbol are not both specified.')
# STEP 3: assembling composite metasymbols together
if debug:
print('Token stream:',tokens)
print('STEP 3: assembling metasymbols according to their possible values.')
tokens = assembleQualifiedNumbers(tokens)
for k in config.keys():