Mercurial > lcfOS
annotate python/ppci/errors.py @ 306:b145f8e6050b
Start on c3 rewrite
author | Windel Bouwman |
---|---|
date | Mon, 09 Dec 2013 19:00:21 +0100 |
parents | 0615b5308710 |
children |
rev | line source |
---|---|
305 | 1 """ |
2 Error handling routines | |
148 | 3 Diagnostic utils |
4 """ | |
5 | |
255 | 6 import logging |
194 | 7 from . import SourceLocation |
8 | |
296 | 9 |
152 | 10 class CompilerError(Exception): |
200 | 11 def __init__(self, msg, loc=None): |
191 | 12 self.msg = msg |
13 self.loc = loc | |
200 | 14 if loc: |
289 | 15 assert type(loc) is SourceLocation, \ |
305 | 16 '{0} must be SourceLocation'.format(type(loc)) |
215 | 17 self.row = loc.row |
18 self.col = loc.col | |
19 else: | |
251
6ed3d3a82a63
Added another c3 example. First import attempt
Windel Bouwman
parents:
248
diff
changeset
|
20 self.row = self.col = 0 |
215 | 21 |
191 | 22 def __repr__(self): |
293 | 23 return '"{}"'.format(self.msg) |
1 | 24 |
148 | 25 |
152 | 26 class DiagnosticsManager: |
225 | 27 def __init__(self): |
248 | 28 self.diags = [] |
293 | 29 self.sources = {} |
255 | 30 self.logger = logging.getLogger('diagnostics') |
215 | 31 |
293 | 32 def addSource(self, name, src): |
33 self.logger.info('Adding source {}'.format(name)) | |
34 self.sources[name] = src | |
35 | |
225 | 36 def addDiag(self, d): |
296 | 37 #self.logger.warning(str(d.msg)) |
248 | 38 self.diags.append(d) |
215 | 39 |
225 | 40 def error(self, msg, loc): |
248 | 41 self.addDiag(CompilerError(msg, loc)) |
215 | 42 |
225 | 43 def clear(self): |
248 | 44 del self.diags[:] |
293 | 45 self.sources.clear() |
215 | 46 |
293 | 47 def printErrors(self): |
225 | 48 if len(self.diags) > 0: |
49 print('{0} Errors'.format(len(self.diags))) | |
50 for d in self.diags: | |
293 | 51 self.printError(d) |
148 | 52 |
293 | 53 def printError(self, e): |
54 def printLine(row, txt): | |
55 print(str(row)+':'+txt) | |
295 | 56 print('==============') |
293 | 57 if not e.loc: |
58 print('Error: {0}'.format(e)) | |
59 else: | |
60 if e.loc.filename not in self.sources: | |
61 print('Error: {0}'.format(e)) | |
62 return | |
295 | 63 print("File: {}".format(e.loc.filename)) |
293 | 64 source = self.sources[e.loc.filename] |
65 lines = source.split('\n') | |
66 ro, co = e.row, e.col | |
67 prerow = ro - 2 | |
68 if prerow < 1: | |
69 prerow = 1 | |
70 afterrow = ro + 3 | |
71 if afterrow > len(lines): | |
72 afterrow = len(lines) | |
73 | |
74 # print preceding source lines: | |
75 for r in range(prerow, ro): | |
76 printLine(r, lines[r-1]) | |
77 # print source line containing error: | |
78 printLine(ro, lines[ro-1]) | |
79 print(' '*(len(str(ro)+':')+co-1) + '^ Error: {0}'.format(e.msg)) | |
80 # print trailing source line: | |
81 for r in range(ro+1, afterrow+1): | |
82 printLine(r, lines[r-1]) | |
295 | 83 print('==============') |