/
lci.py
executable file
·539 lines (510 loc) · 14.6 KB
/
lci.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
#!/usr/bin/python
import os
import sys
import glob
from elementtree import ElementTree
# A global flag, if set, LCI will exit with a non-zero status
problem = False
shutup = ' 1> /dev/null 2> /dev/null'
shortcuts = {}
actions = []
testsets = {}
tester = {}
extractor = {}
treeextractor = {}
treeevaluator = {}
targets = {}
parser = {}
evaluator = {}
testset = []
graph_big = []
graph_small = []
log = None
tools = {}
treetools = {}
almostfailed = []
failednode = []
failedarc = []
failedaction = []
def postfix2prefix(post):
# input: 'x.c.b.a'
# output: 'a b c x'
pre = post.split('.')
pre.reverse()
return ' '.join(pre)
def logwrite(s):
log.write(s+'\n')
log.flush()
def sysexit(n):
log.close()
sys.exit(n)
def readxmlconfig (cfg):
config = ElementTree.parse(cfg)
# shortcuts
for xmlnode in config.findall('//shortcut'):
shortcuts[xmlnode.findtext('name')]=expandxml(xmlnode.findall('expansion')[0],{})
# actions
for xmlnode in config.findall('//target/branch/perform'):
if xmlnode.text not in actions:
actions.append(xmlnode.text)
# testset
for xmlnode in config.findall('//testset'):
testsets[xmlnode.findtext('name')]=expandxml(xmlnode.findall('command')[0],{})
# sources
for xmlnode in config.findall('//source'):
extractor[xmlnode.findtext('name')]=expandxml(xmlnode.findall('grammar/extraction')[0],{})
if xmlnode.findall('grammar/parsing'):
parser[xmlnode.findtext('name')]=expandxml(xmlnode.findall('grammar/parsing')[0],{})
if xmlnode.findall('grammar/evaluation'):
evaluator[xmlnode.findtext('name')]=expandxml(xmlnode.findall('grammar/evaluation')[0],{})
if xmlnode.findall('tree/extraction'):
treeextractor[xmlnode.findtext('name')]=expandxml(xmlnode.findall('tree/extraction')[0],{})
if xmlnode.findall('tree/evaluation'):
treeevaluator[xmlnode.findtext('name')]=expandxml(xmlnode.findall('tree/evaluation')[0],{})
tmp = []
for set in xmlnode.findall('testing/set'):
tmp.append(set.text)
tester[xmlnode.findtext('name')]=tmp[:]
# targets
for xmlnode in config.findall('//target'):
name = xmlnode.findtext('name')
targets[name]= [[],'']
for br in xmlnode.findall('branch'):
branch = [br.findtext('input')]
for p in br.findall('perform'):
branch.append(p.text)
targets[name][0].append(branch)
# tools
for xmlnode in config.findall('//tool'):
tools[xmlnode.findtext('name')] = expandxml(xmlnode.findall('grammar')[0],{})
if xmlnode.findall('tree'):
treetools[xmlnode.findtext('name')] = expandxml(xmlnode.findall('tree')[0],{})
print 'Read',len(shortcuts),'shortcuts,',`len(tools)`+'+'+`len(treetools)`,'tools,',len(actions),'actions,',len(targets),'targets,'
print len(testsets),'test sets,',len(extractor),'sources:',len(parser),'parsers &',len(evaluator),'evaluators'
def expandone(tag,text,rep):
if text:
wte = text
else:
wte = tag.replace('expand-','')
if shortcuts.has_key(wte):
return shortcuts[wte]
elif rep.has_key(wte):
return rep[wte]
else:
# postpone expanding
return '%'+wte+'%'
def expandxml (mixed,rep):
s = mixed.text
for tag in mixed.getchildren():
s += expandone(tag.tag,tag.text,rep)
s += tag.tail
return s.strip()
def expanduni(where,rep):
cut = where.split('%')
for i in range(0,len(cut)):
if i%2:
if shortcuts.has_key(cut[i]):
cut[i]=shortcuts[cut[i]]
elif rep.has_key(cut[i]):
cut[i]=rep[cut[i]]
else:
print 'Misused expand, referencing undefined "'+cut[i]+'":'
print '?????',where
sysexit(11)
return ''.join(cut)
def quote(a):
return '"'+a+'"'
def addarc(fromnode,tonode,q,labelnode):
if [fromnode,tonode,q,labelnode] not in graph_big:
graph_big.append([fromnode,tonode,q,labelnode])
def makegraph():
# first we generate a complete picture
for x in targets.keys():
for src in targets[x][0]:
if len(src)==1:
addarc(src[0],x,'','')
else:
name = src[0]
qname = src[0]
for i in range(1,len(src)-1):
addarc(name,name+"'",qname,src[i])
qname += '.'+src[i]
name += "'"
addarc(name,x,qname,src[-1])
# make a simplified one
for x in targets.keys():
for src in targets[x][0]:
graph_small.append([src[0],x])
def dumpgraph(df):
dot = open(df+'_large.dot','w')
dot.write('digraph generated{ {rank=same; node [shape=ellipse, style=bold];')
for x in extractor.keys():
dot.write(quote(x))
if x in failednode:
dot.write(' [color=red]')
elif x in almostfailed:
dot.write(' [color=blue]')
dot.write(';')
dot.write('}\n')
dot.write('node [shape=octagon, style=bold];\n')
for x in targets.keys():
dot.write(quote(x))
if x in failednode:
dot.write(' [color=red]')
dot.write(';')
dot.write('node [shape=box, style=solid];\n')
nodezz=[]
for arc in graph_big:
dot.write(quote(arc[0])+'->'+quote(arc[1]))
if arc[0] not in nodezz:
nodezz.append(arc[0])
if arc[1] not in nodezz:
nodezz.append(arc[1])
par = ''
if arc[3]:
par += 'label="'+arc[3]+'" '
if [arc[2],arc[3]] in failedarc:
par += 'color=red '
if par:
dot.write(' ['+par+']')
dot.write(';\n')
for node in nodezz:
if node not in extractor.keys():
if node not in targets.keys():
if node in failednode:
dot.write(quote(node)+' [color=red];')
elif node in almostfailed:
dot.write(quote(node)+' [color=blue];')
dot.write('}')
dot.close()
run = 'dot -Tpdf '+dot.name+' -o '+df+'_large.pdf'
logwrite(run)
if os.system(run):
print 'Diagram not generated'
problem = True
dot = open(df+'_small.dot','w')
dot.write('digraph generated{ {rank=same;')
for x in extractor.keys():
dot.write(quote(x))
if x in failednode:
dot.write(' [color=red]')
elif x in almostfailed:
dot.write(' [color=blue]')
dot.write(';')
dot.write('}')
dot.write('node [shape=octagon]\n')
for x in targets.keys():
dot.write(quote(x))
if x in failednode:
dot.write(' [color=red]')
elif x in almostfailed:
dot.write(' [color=blue]')
dot.write(';')
for arc in graph_small:
dot.write(quote(arc[0])+'->'+quote(arc[1]))
if arc[0] in failednode and arc[1] in failednode:
dot.write(' [color=red]')
dot.write(';\n')
dot.write('}')
dot.close()
run = 'dot -Tpdf '+dot.name+' -o '+df+'_small.pdf'
logwrite(run)
if os.system(run):
print 'Diagram not generated'
problem = True
def copyfile(x,y):
xh=open(x,'r')
yh=open(y,'w')
yh.writelines(xh.readlines())
xh.close()
yh.close()
def extractall():
for bgf in extractor.keys():
run = extractor[bgf]+' bgf/'+bgf+'.bgf'
logwrite(run)
if os.system(run+shutup):
print 'Extraction failed on',bgf
if os.access('snapshot/'+bgf+'.bgf',os.R_OK):
print 'Rolled back to the saved version, proceeding...'
copyfile('snapshot/'+bgf+'.bgf','bgf/'+bgf+'.bgf')
logwrite('cp snapshot/'+bgf+'.bgf bgf/'+bgf+'.bgf')
almostfailed.append(bgf)
else:
failednode.append(bgf)
problem = True
#sysexit(3)
else:
copyfile('bgf/'+bgf+'.bgf','snapshot/'+bgf+'.bgf')
print 'Extraction finished.'
def validateall():
for bgf in extractor.keys():
if bgf in failednode:
continue
run = tools['validation']+' bgf/'+bgf+'.bgf'
logwrite(run)
if os.system(run+shutup):
problem = True
print 'Validation failed on',bgf
failednode.append(bgf)
#sysexit(3)
print 'Validation finished.'
def preparebgf(cut):
# executes preparational actions (abstract, unerase, etc) before comparison
if len(cut)==1:
return cut[0]
else:
if cut[0] in extractor.keys():
# starting point is a source
curname = cut[0]
else:
# starting point is another target
curname = targets[cut[0]][1]
# action names will be appended:
# x.bgf -> x.corrupt.bgf -> x.corrupt.confuse.bgf -> x.corrupt.confuse.destroy.bgf -> ...
# the very last one will be diffed
ontheroll = True
for a in cut[1:]:
if ontheroll:
run = tools['transformation']+' xbgf/'+a+'.xbgf bgf/'+curname+'.bgf bgf/'+curname+'.'+a+'.bgf'
logwrite(run)
if os.system(run+shutup):
problem = True
print a,'failed on',curname
failedarc.append([curname,a])
failednode.append(cut[0]+"'"*(curname.count('.')+1))
failedaction.append(postfix2prefix(curname+'.'+a))
ontheroll = False
else:
failedarc.append([curname,a])
failednode.append(cut[0]+"'"*(curname.count('.')+1))
failedaction.append(postfix2prefix(curname+'.'+a))
curname += '.'+a
name = postfix2prefix('.'.join(cut))
if name in failedaction:
print 'Failed',name
elif tools.has_key('validation'):
a = tools['validation']+' bgf/'+curname+'.bgf'
logwrite(a)
print 'Performed',name,'-',
if os.system(a+shutup):
problem = True
print 'NOT',
print 'valid'
else:
print 'Performed',name
return curname
def ordertargets():
unordered = targets.keys()[:]
ordered = []
while len(unordered):
for t in unordered:
flag = True
for i in targets[t][0]:
if (i[0] not in ordered) and (i[0] not in extractor.keys()):
flag = False
if flag:
ordered.append(t)
unordered.remove(t)
return ordered
def buildtargets():
for t in ordertargets():
inputs = targets[t][0]
fileinputs = ['']*len(inputs)
for i in range(0,len(inputs)):
fileinputs[i] = preparebgf(inputs[i])
if len(inputs)>1:
# need to diff
diffall(t,fileinputs[0],fileinputs[1:])
# save resulting name
cx = 0
while cx<len(fileinputs):
if not isbad(fileinputs[cx]):
break
cx+=1
if cx<len(fileinputs):
print 'Target',t,'reached as',fileinputs[cx]
targets[t][1] = fileinputs[cx]
else:
# Tough luck: all branches failed
targets[t][1] = t
def isbad(x):
# checks if the file x failed building
for failed in failedarc:
if x == '.'.join(failed):
return True
return False
def diffall(t,car,cdr):
if len(cdr)==1:
run = tools['comparison']+' bgf/'+car+'.bgf bgf/'+cdr[0]+'.bgf'
logwrite(run)
if os.system(run+shutup):
problem = True
print 'Error occured building target',t,'-',car,'differs from',cdr[0]
failednode.append(t)
#sysexit(3)
else:
for head in cdr:
diffall(t,car,[head])
diffall(t,cdr[0],cdr[1:])
def chainXBTF(testcase,steps,t):
fr = testcase
for step in steps:
if step==steps[-1]:
# name it after the target
re = fr.split('.')[0]+'.'+t+'.btf'
else:
# name it as input.transformationName.btf
re = '.'.join(fr.split('.')[:-1])+'.'+step+'.btf'
run = treetools['transformation']+' xbgf/'+step+'.xbgf '+fr+' '+re
logwrite(run)
#print 'Performing coupled',step,'on',fr,'-',
if os.system(run+shutup):
problem = True
print 'Performing coupled',step,'on',ft,'failed'
break
fr = re
tmp = steps[:]
tmp.reverse()
print 'Performed coupled',' '.join(tmp),'on',testcase,
if treetools.has_key('validation'):
run = treetools['validation']+' '+re
if os.system(run+shutup):
problem = True
print '- NOT valid',
else:
print '- valid'
else:
print
def diffBTFs(t):
if len(testsets)<2:
# with one test set there's nothing to diff
return
if not treetools.has_key('comparison'):
# no tree diff tool specified
rturn
basetestset = testsets.keys()[0]
for basetestcase in glob.glob(basetestset+'/*.'+t+'.btf'):
for testset in testsets.keys()[1:]:
for testcase in glob.glob(testset+'/'+basetestcase.split('/')[1]):
run = treetools['comparison']+' '+basetestcase+' '+testcase
print 'Found',basetestcase.split('/')[1],'in',basetestset,'and',testset,'- they',
if os.system(run+shutup):
problem = True
print 'DIFFER'
else:
print 'match'
def convergetestset():
for testset in testsets.keys():
# extracting
print 'Test set',testset,
run = testsets[testset]+' '+testset
logwrite(run)
if os.system(run+shutup):
problem = True
print 'could not be extracted'
continue
print 'extracted'
for src in treeextractor.keys():
for testset in tester[src]:
for testcase in glob.glob(testset+'/*.src'):
run = treeextractor[src]+' '+testcase+' '+testcase+'.btf'
logwrite(run)
print 'Tree extraction from',testcase,
if os.system(run+shutup):
problem = True
print 'failed'
else:
print 'completed'
for t in ordertargets():
for branch in targets[t][0]:
if treeextractor.has_key(branch[0]):
# it's a source, let's check it we have an extracted tree
for testset in tester[branch[0]]:
for testcase in glob.glob(testset+'/*.src.btf'):
chainXBTF(testcase,branch[1:],t)
if targets.has_key(branch[0]):
# it's a target, let's see if we have any test cases arrived at it
for testset in testsets.keys():
for testcase in glob.glob(testset+'/*.'+branch[0]+'.btf'):
chainXBTF(testcase,branch[1:],t)
diffBTFs(t)
final = ordertargets()[-1]
for evaluator in treeevaluator.keys():
pass
def runtestset():
for testset in testsets.keys():
# testing parser
for testcase in glob.glob(testset+'/*.src'):
results={}
for program in parser.keys():
if testset in tester[program]:
run = parser[program]+' '+testcase
logwrite(run)
results[program]=os.system(run+shutup)
print 'Test case',testcase,
if results.values()==[0]*len(results):
print 'passed parsing'
else:
problem = True
print 'failed'
for r in results.keys():
if results[r]:
print r,'did not parse it correctly'
# testing evaluator
for testcase in glob.glob(testset+'/*.run'):
results={}
for program in evaluator.keys():
if testset in tester[program]:
run = evaluator[program]+' '+testcase.replace('.run','.ctx')+' '+testcase+' '+testcase.replace('.run','.val')
logwrite(run)
results[program]=os.system(run+shutup)
print 'Test case',testcase,
if results.values()==[0]*len(results):
print 'passed evaluation'
else:
problem = True
print 'failed'
for r in results.keys():
if results[r]:
print r,'evaluated it differently'
def checkconsistency():
# some simple assertions
# all targets depend on existing targets or sources
for t in targets.keys():
for i in targets[t][0]:
if not (targets.has_key(i[0]) or extractor.has_key(i[0])):
print 'Target',t,'needs',i[0],'which is not defined'
sysexit(7)
# all actions can be found
try:
for a in actions:
open('xbgf/'+a+'.xbgf','r').close()
except IOError, e:
print 'Undefined action used: need',e.filename
#sysexit(8)
if __name__ == "__main__":
print 'Language Covergence Infrastructure v1.11'
if len(sys.argv) == 3:
log = open(sys.argv[1].split('.')[0]+'.log','w')
readxmlconfig(sys.argv[1])
checkconsistency()
makegraph()
extractall()
if tools.has_key('validation'):
validateall()
buildtargets()
print '----- Grammar convergence phase finished. -----'
if testsets:
runtestset()
convergetestset()
print '----- Tree convergence phase finished. -----'
else:
print 'No testing performed.'
dumpgraph(sys.argv[2])
if problem:
sysexit(100)
log.close()
else:
print 'Usage:'
print ' ',sys.argv[0],'<configuration file>','<diagram prefix>'
sysexit(1)