148
|
1 """
|
|
2 Error handling routines
|
|
3 Diagnostic utils
|
|
4 """
|
|
5
|
152
|
6 class CompilerError(Exception):
|
148
|
7 def __init__(self, msg, loc):
|
1
|
8 self.msg = msg
|
148
|
9 self.loc = loc
|
1
|
10 def __repr__(self):
|
152
|
11 return 'Compilererror {0} at {1}'.format(self.msg, self.loc)
|
1
|
12
|
|
13 def printError(source, e):
|
|
14 def printLine(row, txt):
|
|
15 print(str(row)+':'+txt)
|
148
|
16 if e.loc.row == 0:
|
1
|
17 print('Error: {0}'.format(e.msg))
|
|
18 else:
|
|
19 lines = source.split('\n')
|
148
|
20 ro, co = e.loc.row, e.loc.col
|
|
21 prerow = ro - 2
|
1
|
22 if prerow < 1:
|
|
23 prerow = 1
|
148
|
24 afterrow = ro + 3
|
1
|
25 if afterrow > len(lines):
|
|
26 afterrow = len(lines)
|
|
27
|
|
28 # print preceding source lines:
|
148
|
29 for r in range(prerow, ro):
|
1
|
30 printLine(r, lines[r-1])
|
|
31 # print source line containing error:
|
148
|
32 printLine(ro, lines[ro-1])
|
|
33 print(' '*(len(str(ro)+':')+co-1) + '^ Error: {0}'.format(e.msg))
|
1
|
34 # print trailing source line:
|
148
|
35 for r in range(ro+1, afterrow+1):
|
1
|
36 printLine(r, lines[r-1])
|
148
|
37
|
152
|
38 class DiagnosticsManager:
|
148
|
39 def __init__(self):
|
|
40 self.diags = []
|
152
|
41 def addDiag(self, d):
|
148
|
42 self.diags.append(d)
|
152
|
43 def error(self, msg, loc):
|
|
44 self.addDiag(CompilerError(msg, loc))
|
148
|
45
|