/
__init__.py
489 lines (440 loc) · 16.3 KB
/
__init__.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
"""Lang
This module provides functions and parsers that are common for
all languages.
"""
import os
import re
import sys
import textwrap
from excentury.command import error, trace, date, exec_cmd
from excentury.core.load_text import TextParser
# pylint: disable=R0902, R0903
class Function(object):
"""Object to store a function defined in a xcpp file. """
def __init__(self, name, num):
self.name = name
self.num = num
self.param = None
self.body = None
self.ret = None
self.doc = None
self.out = None
self.preamble = ''
self.epilog = ''
class XCFile(object):
"""Object to store the information of an xcpp file. """
def __init__(self):
self.docstring = None
self.pre_xc = None
self.preamble = None
self.function = None
self.epilog = ''
def split_at(delimiter, text, opens='<(', closes='>)', quotes='"\''):
"""Custom function to split at commas. Taken from stackoverflow
http://stackoverflow.com/a/20599372/788553"""
result = []
buff = ""
level = 0
is_quoted = False
for char in text:
if char in delimiter and level == 0 and not is_quoted:
result.append(buff)
buff = ""
else:
buff += char
if char in opens:
level += 1
elif char in closes:
level -= 1
elif char in quotes:
is_quoted = not is_quoted
if not buff == "":
result.append(buff)
return result
def clean_param(par):
"""Returns a dictionary containing the parameter's 'type',
'name', 'desc', and an optional key 'sample'. """
param = {'type': par[0], 'desc': par[2][1:-1]}
index = par[1].find('(')
if index == -1:
param['name'] = '`%s`' % par[1]
param['ctor'] = ''
else:
param['name'] = '`%s`' % par[1][:index]
param['ctor'] = par[1][index:]
if len(par) > 3:
param['sample'] = par[3]
return param
class FileParser(object):
"""Object designed to parse an xcpp file. """
def __init__(self, fname):
self.fname = fname
self.num = 0
self.text = open(fname, 'r').read()
self.caret = 0
self.end = len(self.text)
self.pos = [1, 1]
self.tmp = ''
self.wrapper = textwrap.TextWrapper(width=70,
break_long_words=False)
def update(self, index):
"""Changes the position of the `caret` and updates `pos`.
This function assumes that you are moving forward. Do not
update to an index which is less than the current position of
the caret. """
if index == self.caret:
return
nlines = self.text.count('\n', self.caret, index)
self.pos[0] += nlines
if nlines > 0:
self.pos[1] = index - self.text.rfind('\n', self.caret, index)
else:
self.pos[1] += index - self.caret
self.caret = index
def move_caret(self, num):
"""Move the caret num spaces. """
self.update(self.caret+num)
def error(self, pos, msg):
"""Exit with a message. """
name = self.fname
tmp = 'ERROR in Line %d, Column %d ' \
'in %s: \n ' % (pos[0], pos[1], name)
sys.stderr.write(tmp)
tmp = re.sub("\\s+", " ", msg)
sys.stderr.write('\n '.join(self.wrapper.wrap(tmp)))
sys.stderr.write('\n\n')
sys.exit(1)
def str(self, num):
"""Return num characters from the parser current position. """
return self.text[self.caret:self.caret+num]
def find(self, txt, dt_=0):
"""Find the sting txt from the current position plus dt. """
return self.text.find(txt, self.caret+dt_)
def get_preamble(self):
"""Read the preamble. To be called right after the docstring.
"""
if self.text[self.caret:self.caret+3] == '---':
index = self.find('\n')
if index == -1:
index = self.end
self.update(index+1)
return ''
index = self.find('\n---')
if index == -1:
msg = 'did not find `\\n---` in xcpp file, this is the ' \
'starting point for function definitions\n'
self.error(self.pos, msg)
preamble = self.text[self.caret:index+1].strip()
self.update(index+1)
index = self.find('\n')
if index == -1:
index = self.end
self.update(index+1)
if preamble != "":
preamble += "\n"
return preamble
def get_func_preamble(self):
"""Read the function preamble. """
if self.text[self.caret] == '@':
return ''
index = self.find('\n@')
if index == -1:
index = self.end
preamble = self.text[self.caret:index+1].strip()
self.update(index+1)
if preamble != "":
preamble += "\n"
return preamble
def _skip_and_update(self):
"""Skip a line. """
index = self.find('\n')
if index == -1:
index = self.end
self.update(index+1)
def get_func_epilog(self):
"""Read the function epilog. """
if self.text[self.caret:self.caret+3] == '---':
self._skip_and_update()
return ''
index = self.find('\n---')
def_index = self.find('@def{')
if index == -1:
if def_index != -1:
self.error(self.pos, "Missing `---` before `@def`.")
self.error(self.pos, "Missing `---` for function epilog.")
elif def_index == -1:
epilog = self.text[self.caret:index+1].strip()
self.update(index+1)
self._skip_and_update()
self.tmp = self.text[self.caret:self.end].strip()
self.update(self.end)
return epilog
elif def_index < index:
self.error(self.pos, "`---` must appear before `@def`.")
epilog = self.text[self.caret:index+1].strip()
self.update(index+1)
self._skip_and_update()
return epilog
def skip_space(self):
"""Skip white spaces. """
index = self.caret
while self.text[index:index+1] in [' ', '\t', '\n']:
index += 1
self.update(index)
def in_between(self, start, end, msg_start, msg_end):
"""Given a string start and string end it returns the
contents between <start>...<end>. If the current position
does not begin with start then it raises an error. If
msg_start is None then the function returns None in case the
text does not start with start. """
if self.str(len(start)) != start:
if msg_start is None:
return None
else:
self.error(self.pos, msg_start)
self.move_caret(len(start))
index = self.find(end)
if index == -1:
self.error(self.pos, msg_end)
content = self.text[self.caret:index]
self.update(index+len(end))
return content
def get_function_name(self):
"""Read the name. """
msg_start = "@def{function_name} expected..."
msg_end = "Missing '}' while reading name..."
name = self.in_between('@def{', '}', msg_start, msg_end)
self.skip_space()
return name
def get_docstring(self):
"""Read a documentation string. """
msg_start = "docstring expected..."
msg_end = 'Missing \'"""\' while reading docstring...'
docstring = self.in_between('"""', '"""', msg_start, msg_end)
self.skip_space()
return docstring.strip()
def get_pre_xc(self):
"""Read a block after the docstring that starts with [[ and
ends with ]]. This is code that will be placed before the
inclusion of excentury. """
if self.text[self.caret:self.caret+2] != '[[':
return ''
msg_end = "Missing ']]' while reading pre-xc..."
content = self.in_between('[[', ']]', "", msg_end).strip()
self.skip_space()
if content != "":
content += '\n'
return content
def get_params(self):
"""Read a parameter. """
params = list()
msg_end = "Missing '}' while reading param..."
pos = list(self.pos)
param = self.in_between('@param{', '}', None, msg_end)
while param is not None:
self.skip_space()
par = split_at(',', param)
if len(par) < 3:
self.error(pos, "3 arguments expected...")
params.append(clean_param([ele.strip() for ele in par]))
pos = list(self.pos)
param = self.in_between('@param{', '}', None, msg_end)
return params
def get_body(self):
"""Read the function body. """
msg_start = "@body[[ expected..."
msg_end = "Missing ']]' while body..."
body = self.in_between('@body[[', ']]', msg_start, msg_end)
self.skip_space()
return body
def get_ret(self):
"""Read the return body. """
msg_end = "Missing '}' while ret..."
out = self.in_between('@ret{', '}', None, msg_end)
msg_end = "Missing ']]' while ret..."
if out is None:
msg_start = "@ret[[ expected..."
ret = self.in_between('@ret[[', ']]', msg_start, msg_end)
out = 'stdout'
else:
msg_start = "[[ expected..."
ret = self.in_between('[[', ']]', msg_start, msg_end)
return out, ret
def get_function(self):
"""Read a function from the file. """
self.num += 1
func = Function(self.get_function_name(), self.num)
func.doc = self.get_docstring()
func.param = self.get_params()
func.body = self.get_body()
func.out, func.ret = self.get_ret()
return func
def parse(self):
"""Return the information stored in the xcpp file. """
xcfile = XCFile()
xcfile.docstring = self.get_docstring()
xcfile.pre_xc = self.get_pre_xc()
xcfile.preamble = self.get_preamble()
xcfile.function = list()
while self.caret < self.end:
preamble = self.get_func_preamble()
func = self.get_function()
func.preamble = preamble
func.epilog = self.get_func_epilog()
xcfile.function.append(func)
xcfile.epilog = self.tmp
return xcfile
def format_input(param):
"""Return a string with all the inputs property formatted. """
tmp1 = ' {type} {var}{ctor}; XC_LI_.load({var});\n'
tmp2 = ' {type} {var}{ctor}; XC_LI_.load({var}, {sample});\n'
inputs = ''
for par in param:
if 'sample' in par:
inputs += tmp2.format(type=par['type'],
var=par['name'][1:-1],
ctor=par['ctor'],
sample=par['sample'])
else:
inputs += tmp1.format(type=par['type'],
var=par['name'][1:-1],
ctor=par['ctor'])
return inputs
def format_return(ret):
"""Given the return statement, replace all instances of @ret with
XC_DI_. """
ret = ret.strip()
res = ''
caret = 0
index = ret.find('@ret{', caret)
while index != -1:
res += ret[caret:index]
caret = index + 5
res += 'XC_DI_.dump('
index_end = ret.find('}', caret)
if index == -1:
index = len(ret)
args = [ele.strip() for ele in ret[caret:index_end].split(',')]
if len(args) == 2 and args[1][0] not in ['"', "'"]:
args.insert(1, '"%s"' % args[0])
elif len(args) == 1:
args.append('"%s"' % args[0].strip())
res += '%s);' % ', '.join(args)
caret = index_end+1
index = ret.find('@ret{', caret)
res += ret[caret:]
return res
def gen_cmd(cfg, lang, debug=None):
"""Given the configuration dictionary, it generates most of the
command to compile a cpp program. """
root = cfg['xcpp']['root']
cxx = cfg[lang]['cxx']
opt = '%s ' % cfg[lang]['opt'].strip()
if debug is None or debug == 0:
if cfg[lang]['debug'] == '0':
dbg = ''
else:
dbg = '-DDEBUG=%s ' % cfg[lang]['debug']
else:
dbg = '-DDEBUG=%d ' % debug
tmpl = [i if i[0:1] != '/' else os.path.join(root, i)
for i in cfg[lang].get('cxxinc', '').split(':')]
inc = ['-I%s/%s' % (root, i) for i in tmpl]
inc = ' '.join(inc)
inc = '' if inc == '-I' else '%s ' % inc
tmpl = [i if i[0:1] != '/' else os.path.join(root, i)
for i in cfg[lang].get('cxxlib', '').split(':')]
lib = ['-L%s/%s' % (root, i) for i in tmpl]
lib = ' '.join(lib)
lib = '' if lib == '-L' else '%s ' % lib
return '%s %s%s%s%s' % (cxx, dbg, opt, inc, lib)
def gen_input_file(xcfile, filename):
"""Generate the input file and return the name of the file it
prints along with a dictionary containing the datatypes it
contains. """
funcpre = ''.join([func.preamble for func in xcfile.function])
cont = """// Temporary file generated on {date} by xcpp.
{preamble}{funcpre}
int main() {{
excentury::TextInterface<excentury::dump_mode> XC_DI_(stdout);
{tmp} XC_DI_.close();
}}
""".format(date=date(), pre_xc=xcfile.pre_xc, tmp='{XC-INPUTS}',
preamble=xcfile.preamble, funcpre=funcpre)
var = dict()
num = 1
tmp1 = ' {type} {var}{ctor}; XC_DI_.dump({var}, "{var}");\n'
tmp2 = ' {type} {var}{ctor}; XC_DI_.dump({var}, "{var}", {sample});\n'
inputs = ''
for func in xcfile.function:
for par in func.param:
if par['type'] not in var:
vname = 'var%d_%s' % (num, par['name'][1:-1])
var[par['type']] = vname
if 'sample' in par:
sample = par['sample'].replace(par['name'][1:-1],
vname)
inputs += tmp2.format(type=par['type'], var=vname,
ctor=par['ctor'],
sample=sample)
else:
inputs += tmp1.format(type=par['type'], var=vname,
ctor=par['ctor'])
num += 1
fname = 'inputs-%s.cpp' % filename
trace('+ writing temporary file %s ... ' % fname)
with open(fname, 'w') as tmp:
tmp.write(cont.replace('{XC-INPUTS}', inputs))
trace('done\n')
return fname, var
def _make_map(var, fvar):
"""Helper function to collect the input map. """
info = dict()
for key, val in var.iteritems():
for fkey, fval in fvar.iteritems():
if key == fval:
info[fkey] = val
break
return info
def extract_name(filename):
"""Obtain the name of the file. """
return os.path.splitext(os.path.basename(filename))[0]
def check_inputs(xcfile, cfg, lang):
"""Make an executable with all the inputs the xcpp file uses
and make sure that all of them are valid. Return a dictionary
with the info on all the inputs. """
fname = cfg['xcpp']['filename']
fname, fvar = gen_input_file(xcfile, fname)
cmd = '%s%s ' % (gen_cmd(cfg, lang, 1), fname)
trace(' - compiling %s ... ' % fname)
out, err, _ = exec_cmd(cmd)
if err != '':
msg = "ERROR: The command\n%s\n\nreturned the following " \
"error:\n%s" % (str(cmd), str(err))
error(msg)
trace('done\n')
trace(' - running executable ... ')
out, err, _ = exec_cmd('./a.out')
if err != '':
msg = "\nERROR: The command `%s` returned the following " \
"error:\n%s" % ('./a.out', str(err))
error(msg)
trace('done\n')
var, defs = TextParser(out).parse_info()
info = _make_map(var, fvar)
os.remove('a.out')
os.remove(fname)
return info, defs
def write_file(in_fname, contents):
"""Helper function to write contents to in_fname. """
make_new = True
if os.path.exists(in_fname):
tmp = open(in_fname, 'r').read()
if tmp[tmp.find('\n'):] == contents[contents.find('\n'):]:
make_new = False
if make_new:
with open(in_fname, 'w') as tmp:
tmp.write(contents)
trace('[NEW CONTENT]\n')
else:
trace('[NO CHANGE]\n')