Mercurial > lcfOS
annotate python/ppci/errors.py @ 247:dd8bbb963458
project remove
author | Windel Bouwman |
---|---|
date | Fri, 26 Jul 2013 10:44:26 +0200 |
parents | 1c7364bd74c7 |
children | b10d46e5c8dd |
rev | line source |
---|---|
148 | 1 """ |
2 Error handling routines | |
3 Diagnostic utils | |
4 """ | |
5 | |
194 | 6 from . import SourceLocation |
7 | |
152 | 8 class CompilerError(Exception): |
200 | 9 def __init__(self, msg, loc=None): |
191 | 10 self.msg = msg |
11 self.loc = loc | |
200 | 12 if loc: |
13 assert type(loc) is SourceLocation, '{0} must be SourceLocation'.format(type(loc)) | |
215 | 14 self.row = loc.row |
15 self.col = loc.col | |
16 else: | |
17 self.row = self.col = None | |
18 | |
191 | 19 def __repr__(self): |
215 | 20 if self.row: |
21 return 'Compilererror: "{0}" at row {1}'.format(self.msg, self.row) | |
200 | 22 else: |
23 return 'Compilererror: "{0}"'.format(self.msg) | |
1 | 24 |
25 def printError(source, e): | |
26 def printLine(row, txt): | |
27 print(str(row)+':'+txt) | |
148 | 28 if e.loc.row == 0: |
1 | 29 print('Error: {0}'.format(e.msg)) |
30 else: | |
31 lines = source.split('\n') | |
215 | 32 ro, co = e.row, e.col |
148 | 33 prerow = ro - 2 |
1 | 34 if prerow < 1: |
35 prerow = 1 | |
148 | 36 afterrow = ro + 3 |
1 | 37 if afterrow > len(lines): |
38 afterrow = len(lines) | |
39 | |
40 # print preceding source lines: | |
148 | 41 for r in range(prerow, ro): |
1 | 42 printLine(r, lines[r-1]) |
43 # print source line containing error: | |
148 | 44 printLine(ro, lines[ro-1]) |
45 print(' '*(len(str(ro)+':')+co-1) + '^ Error: {0}'.format(e.msg)) | |
1 | 46 # print trailing source line: |
148 | 47 for r in range(ro+1, afterrow+1): |
1 | 48 printLine(r, lines[r-1]) |
148 | 49 |
152 | 50 class DiagnosticsManager: |
225 | 51 def __init__(self): |
148 | 52 self.diags = [] |
215 | 53 |
225 | 54 def addDiag(self, d): |
148 | 55 self.diags.append(d) |
215 | 56 |
225 | 57 def error(self, msg, loc): |
152 | 58 self.addDiag(CompilerError(msg, loc)) |
215 | 59 |
225 | 60 def clear(self): |
182
e9b27f7193e3
Replace clear function by function also supported in python 3.2
Windel Bouwman
parents:
172
diff
changeset
|
61 del self.diags[:] |
215 | 62 |
225 | 63 def printErrors(self, src): |
64 if len(self.diags) > 0: | |
65 print('==============') | |
66 print('{0} Errors'.format(len(self.diags))) | |
67 for d in self.diags: | |
68 print('==============') | |
69 printError(src, d) | |
70 print('==============') | |
148 | 71 |