/
linter.py
509 lines (445 loc) · 17.2 KB
/
linter.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
# import ast
# import json
# import ruamel.yaml as ry
# from ruamel.yaml.comments import CommentedSeq
# from dolo.compiler.symbolic import check_expression
# from dolo.compiler.recipes import recipes
# from dolo.misc.termcolor import colored
# class Compare:
# def __init__(self):
# self.d = {}
# def compare(self, A, B):
# if isinstance(A, ast.Name) and (A.id[0] == '_'):
# if A.id not in self.d:
# self.d[A.id] = B
# return True
# else:
# return self.compare(self.d[A.id], B)
# if not (A.__class__ == B.__class__):
# return False
# if isinstance(A, ast.Name):
# return A.id == B.id
# elif isinstance(A, ast.Call):
# if not self.compare(A.func, B.func):
# return False
# if not len(A.args) == len(B.args):
# return False
# for i in range(len(A.args)):
# if not self.compare(A.args[i], B.args[i]):
# return False
# return True
# elif isinstance(A, ast.Num):
# return A.n == B.n
# elif isinstance(A, ast.Expr):
# return self.compare(A.value, B.value)
# elif isinstance(A, ast.Module):
# if not len(A.body) == len(B.body):
# return False
# for i in range(len(A.body)):
# if not self.compare(A.body[i], B.body[i]):
# return False
# return True
# elif isinstance(A, ast.BinOp):
# if not isinstance(A.op, B.op.__class__):
# return False
# if not self.compare(A.left, B.left):
# return False
# if not self.compare(A.right, B.right):
# return False
# return True
# elif isinstance(A, ast.UnaryOp):
# if not isinstance(A.op, B.op.__class__):
# return False
# return self.compare(A.operand, B.operand)
# elif isinstance(A, ast.Subscript):
# if not self.compare(A.value, B.value):
# return False
# return self.compare(A.slice, B.slice)
# elif isinstance(A, ast.Index):
# return self.compare(A.value, B.value)
# elif isinstance(A, ast.Compare):
# if not self.compare(A.left, B.left):
# return False
# if not len(A.ops) == len(B.ops):
# return False
# for i in range(len(A.ops)):
# if not self.compare(A.ops[i], B.ops[i]):
# return False
# if not len(A.comparators) == len(B.comparators):
# return False
# for i in range(len(A.comparators)):
# if not self.compare(A.comparators[i], B.comparators[i]):
# return False
# return True
# elif isinstance(A, ast.In):
# return True
# elif isinstance(A, (ast.Eq, ast.LtE)):
# return True
# else:
# print(A.__class__)
# raise Exception("Not implemented")
# def compare_strings(a, b):
# t1 = ast.parse(a)
# t2 = ast.parse(b)
# comp = Compare()
# val = comp.compare(t1, t2)
# return val
# def match(m, s):
# if isinstance(m, str):
# m = ast.parse(m).body[0].value
# if isinstance(s, str):
# s = ast.parse(s).body[0].value
# comp = Compare()
# val = comp.compare(m, s)
# d = comp.d
# if len(d) == 0:
# return val
# else:
# return d
# known_symbol_types = {
# 'dtcc': recipes['dtcc']['symbols'],
# }
# class ModelException(Exception):
# type = 'error'
# def check_symbol_validity(s):
# import ast
# val = ast.parse(s).body[0].value
# assert (isinstance(val, ast.Name))
# def check_symbols(data):
# # can raise three types of exceptions
# # - unknown symbol
# # - invalid symbol
# # - already declared
# # add: not declared if missing 'states', 'controls' ?
# exceptions = []
# symbols = data['symbols']
# cm_symbols = symbols
# model_type = 'dtcc'
# already_declared = {} # symbol: symbol_type, position
# for key, values in cm_symbols.items():
# # (start_line, start_column, end_line, end_column) of the key
# if key not in known_symbol_types[model_type]:
# l0, c0, l1, c1 = cm_symbols.lc.data[key]
# exc = ModelException(
# "Unknown symbol type '{}'".format(
# key, model_type))
# exc.pos = (l0, c0, l1, c1)
# # print(l0,c0,l1,c1)
# exceptions.append(exc)
# assert (isinstance(values, CommentedSeq))
# for i, v in enumerate(values):
# (l0, c0) = values.lc.data[i]
# length = len(v)
# l1 = l0
# c1 = c0 + length
# try:
# check_symbol_validity(v)
# except:
# exc = ModelException("Invalid symbol '{}'".format(v))
# exc.pos = (l0, c0, l1, c1)
# exceptions.append(exc)
# if v in already_declared:
# ll = already_declared[v]
# exc = ModelException(
# "Symbol '{}' already declared as '{}'. (pos {})".format(
# v, ll[0], (ll[1][0] + 1, ll[1][1])))
# exc.pos = (l0, c0, l1, c1)
# exceptions.append(exc)
# else:
# already_declared[v] = (key, (l0, c0))
# return exceptions
# def check_equations(data):
# model_type = data['model_type']
# pos0 = data.lc.data['equations']
# equations = data['equations']
# exceptions = []
# recipe = recipes[model_type]
# specs = recipe['specs']
# for eq_type in specs.keys():
# if (eq_type not in equations) and (not specs[eq_type].get(
# 'optional', True)):
# exc = ModelException("Missing equation type {}.".format(eq_type))
# exc.pos = pos0
# exceptions.append(exc)
# already_declared = {}
# unknown = []
# for eq_type in equations.keys():
# pos = equations.lc.data[eq_type]
# if eq_type not in specs:
# exc = ModelException("Unknown equation type {}.".format(eq_type))
# exc.pos = pos
# exceptions.append(exc)
# unknown.append(eq_type)
# # BUG: doesn't produce an error when a block is declared twice
# # should be raised by ruaml.yaml ?
# elif eq_type in already_declared.keys():
# exc = ModelException(
# "Equation type {} declared twice at ({})".format(eq_type, pos))
# exc.pos = pos
# exceptions.append(exc)
# else:
# already_declared[eq_type] = pos
# for eq_type in [k for k in equations.keys() if k not in unknown]:
# for n, eq in enumerate(equations[eq_type]):
# eq = eq.replace('<=', '<').replace('==',
# '=').replace('=', '==').replace(
# '<', '<=')
# # print(eq)
# pos = equations[eq_type].lc.data[n]
# try:
# ast.parse(eq)
# except SyntaxError as e:
# exc = ModelException("Syntax Error.")
# exc.pos = [
# pos[0], pos[1] + e.offset, pos[0], pos[1] + e.offset
# ]
# exceptions.append(exc)
# # TEMP: incorrect ordering
# if specs[eq_type].get('target'):
# for n, eq in enumerate(equations[eq_type]):
# eq = eq.replace('<=', '<').replace('==', '=').replace(
# '=', '==').replace('<', '<=')
# pos = equations[eq_type].lc.data[n]
# lhs_name = str.split(eq, '=')[0].strip()
# target = specs[eq_type]['target'][0]
# if lhs_name not in data['symbols'][target]:
# exc = ModelException(
# "Undeclared assignement target '{}'. Add it to '{}'.".
# format(lhs_name, target))
# exc.pos = [pos[0], pos[1], pos[0], pos[1] + len(lhs_name)]
# exceptions.append(exc)
# # if n>len(data['symbols'][target]):
# else:
# right_name = data['symbols'][target][n]
# if lhs_name != right_name:
# exc = ModelException(
# "Left hand side should be '{}' instead of '{}'.".
# format(right_name, lhs_name))
# exc.pos = [
# pos[0], pos[1], pos[0], pos[1] + len(lhs_name)
# ]
# exceptions.append(exc)
# # temp
# return exceptions
# def check_definitions(data):
# if 'definitions' not in data:
# return []
# definitions = data['definitions']
# if definitions is None:
# return []
# exceptions = []
# known_symbols = sum([[*v] for v in data['symbols'].values()], [])
# allowed_symbols = {v: (0, ) for v in known_symbols} # TEMP
# for p in data['symbols']['parameters']:
# allowed_symbols[p] = (0, )
# new_definitions = dict()
# for k, v in definitions.items():
# pos = definitions.lc.data[k]
# if k in known_symbols:
# exc = ModelException(
# 'Symbol {} has already been defined as a model symbol.'.format(
# k))
# exc.pos = pos
# exceptions.append(exc)
# continue
# if k in new_definitions:
# exc = ModelException(
# 'Symbol {} cannot be defined twice.'.format(k))
# exc.pos = pos
# exceptions.append(exc)
# continue
# try:
# check_symbol_validity(k)
# except:
# exc = ModelException("Invalid symbol '{}'".format(k))
# exc.pos = pos
# exceptions.append(exc)
# # pos = equations[eq_type].lc.data[n]
# try:
# expr = ast.parse(str(v))
# # print(allowed_symbols)
# check = check_expression(expr, allowed_symbols)
# # print(check['problems'])
# for pb in check['problems']:
# name, t, offset, err_type = [pb[0], pb[1], pb[2], pb[3]]
# if err_type == 'timing_error':
# exc = Exception(
# 'Timing for variable {} could not be determined.'.
# format(pb[0]))
# elif err_type == 'incorrect_timing':
# exc = Exception(
# 'Variable {} cannot have time {}. (Allowed: {})'.
# format(name, t, pb[4]))
# elif err_type == 'unknown_function':
# exc = Exception(
# 'Unknown variable/function {}.'.format(name))
# elif err_type == 'unknown_variable':
# exc = Exception(
# 'Unknown variable/parameter {}.'.format(name))
# else:
# print(err_type)
# exc.pos = (pos[0], pos[1] + offset, pos[0],
# pos[1] + offset + len(name))
# exc.type = 'error'
# exceptions.append(exc)
# new_definitions[k] = v
# allowed_symbols[k] = (0, ) # TEMP
# # allowed_symbols[k] = None
# except SyntaxError as e:
# pp = pos # TODO: find right mark for pp
# exc = ModelException("Syntax Error.")
# exc.pos = [pp[0], pp[1] + e.offset, pp[0], pp[1] + e.offset]
# exceptions.append(exc)
# return exceptions
# def check_calibration(data):
# # what happens here if symbols are not clean ?
# symbols = data['symbols']
# pos0 = data.lc.data['calibration']
# calibration = data['calibration']
# exceptions = []
# all_symbols = []
# for v in symbols.values():
# all_symbols += v
# for s in all_symbols:
# if (s not in calibration.keys()) and (s not in symbols["exogenous"]):
# # should skip invalid symbols there
# exc = ModelException(
# "Symbol {} has no calibrated value.".format(s))
# exc.pos = pos0
# exc.type = 'warning'
# exceptions.append(exc)
# for s in calibration.keys():
# val = str(calibration[s])
# try:
# ast.parse(val)
# except SyntaxError as e:
# pos = calibration.lc.data[s]
# exc = ModelException("Syntax Error.")
# exc.pos = [pos[0], pos[1] + e.offset, pos[0], pos[1] + e.offset]
# exceptions.append(exc)
# return exceptions
# def check_all(data):
# def serious(exsc):
# return ('error' in [e.type for e in exsc])
# exceptions = check_infos(data)
# if serious(exceptions):
# return exceptions
# exceptions = check_symbols(data)
# if serious(exceptions):
# return exceptions
# exceptions += check_definitions(data)
# if serious(exceptions):
# return exceptions
# exceptions += check_equations(data)
# if serious(exceptions):
# return exceptions
# exceptions += check_calibration(data)
# if serious(exceptions):
# return exceptions
# return exceptions
# def human_format(err):
# err_type = err['type']
# err_type = colored(
# err_type, color=('red' if err_type == 'error' else 'yellow'))
# err_range = str([e + 1 for e in err['range'][0]])[1:-1]
# return '{:7}: {:6}: {}'.format(err_type, err_range, err['text'])
# def check_infos(data):
# exceptions = []
# if 'model_type' in data:
# model_type = data['model_type']
# if model_type not in ['dtcc', 'dtmscc', 'dtcscc', 'dynare']:
# exc = ModelException('Uknown model type: {}.'.format(
# str(model_type)))
# exc.pos = data.lc.data['model_type']
# exc.type = 'error'
# exceptions.append(exc)
# else:
# model_type = 'dtcc'
# data['model_type'] = 'dtcc'
# # exc = ModelException("Missing field: 'model_type'.")
# # exc.pos = (0,0,0,0)
# # exc.type='error'
# # exceptions.append(exc)
# if 'name' not in data:
# exc = ModelException("Missing field: 'name'.")
# exc.pos = (0, 0, 0, 0)
# exc.type = 'warning'
# exceptions.append(exc)
# return exceptions
# def lint(txt, source='<string>', format='human', catch_exception=False):
# # raise ModelException if it doesn't work correctly
# if isinstance(txt, str):
# try:
# data = ry.load(txt, ry.RoundTripLoader)
# except Exception as exc:
# if not catch_exception:
# raise exc
# return [] # should return parse error
# else:
# # txt is then assumed to be a ruamel structure
# data = txt
# if not ('symbols' in data or 'equations' in data or 'calibration' in data):
# # this is probably not a yaml filename
# output = []
# else:
# try:
# exceptions = check_all(data)
# except Exception as e:
# if not catch_exception:
# raise(e)
# exc = ModelException("Linter Error: Uncaught Exception.")
# exc.pos = [0, 0, 0, 0]
# exc.type = 'error'
# exceptions = [exc]
# output = []
# for k in exceptions:
# try:
# err_type = k.type
# except:
# err_type = 'error'
# output.append({
# 'type':
# err_type,
# 'source':
# source,
# 'range': ((k.pos[0], k.pos[1]), (k.pos[2], k.pos[3])),
# 'text':
# k.args[0]
# })
# if format == 'json':
# return (json.dumps(output))
# elif format == 'human':
# return (str.join("\n", [human_format(e) for e in output]))
# elif not format:
# return output
# else:
# raise ModelException("Unkown format {}.".format(format))
# TODO:
# - check name (already defined by smbdy else ?)
# - description: ?
# - calibration:
# - incorrect key
# - warning if not a known symbol ?
# - not a recognized identifier
# - defined twice
# - impossible to solve in closed form (depends on ...)
# - incorrect equation
# - grammatically incorrect
# - contains timed variables
# - warnings:
# - missing values
# - equations: symbols already known (beware of speed issues)
# - unknown group of equations
# - incorrect syntax
# - undeclared variable (and not a function)
# - indexed parameter
# - incorrect order
# - incorrect complementarities
# - incorrect recipe: unexpected symbol type
# - nonzero residuals (warning, to be done without compiling)
# - options: if present
# - approximation_space:
# - inconsistent boundaries
# - must equal number of states
# - distribution:
# - same size as shocks