comparison python/ppci/errors.py @ 148:e5263f74b287

Added c3 language frontend initial parser
author Windel Bouwman
date Fri, 01 Mar 2013 10:24:01 +0100
parents 4e79484a9d47
children b73bc14a3aa3
comparison
equal deleted inserted replaced
147:4e79484a9d47 148:e5263f74b287
1 """ Error handling routines """ 1 """
2 Error handling routines
3 Diagnostic utils
4 """
5
6 from collections import namedtuple
7
8 SourceLocation = namedtuple('SourceLocation', ['row', 'col'])
9 SourceRange = namedtuple('SourceRange', ['p1', 'p2'])
2 10
3 class CompilerException(Exception): 11 class CompilerException(Exception):
4 def __init__(self, msg, row=0, col=0, filename=None): 12 def __init__(self, msg, loc):
5 self.msg = msg 13 self.msg = msg
6 self.row = row 14 self.loc = loc
7 self.col = col
8 self.filename = filename
9 def __repr__(self): 15 def __repr__(self):
10 return self.msg 16 return 'error {0} at {1}'.format(self.msg, self.loc)
11 def __str__(self): 17 def __str__(self):
12 return self.msg 18 return 'error {0} at {1}'.format(self.msg, self.loc)
13 19
14 class ErrorNode: 20 class ErrorNode:
15 def __init__(self, row, col, msg): 21 def __init__(self, row, col, msg):
16 self.row, self.col = row,col 22 self.row, self.col = row,col
17 self.msg = msg 23 self.msg = msg
23 raise CompilerException(msg, node.row, node.col) 29 raise CompilerException(msg, node.row, node.col)
24 30
25 def printError(source, e): 31 def printError(source, e):
26 def printLine(row, txt): 32 def printLine(row, txt):
27 print(str(row)+':'+txt) 33 print(str(row)+':'+txt)
28 if e.row == 0: 34 if e.loc.row == 0:
29 print('Error: {0}'.format(e.msg)) 35 print('Error: {0}'.format(e.msg))
30 else: 36 else:
31 lines = source.split('\n') 37 lines = source.split('\n')
32 prerow = e.row - 3 38 ro, co = e.loc.row, e.loc.col
39 prerow = ro - 2
33 if prerow < 1: 40 if prerow < 1:
34 prerow = 1 41 prerow = 1
35 afterrow = e.row + 3 42 afterrow = ro + 3
36 if afterrow > len(lines): 43 if afterrow > len(lines):
37 afterrow = len(lines) 44 afterrow = len(lines)
38 45
39 # print preceding source lines: 46 # print preceding source lines:
40 for r in range(prerow, e.row): 47 for r in range(prerow, ro):
41 printLine(r, lines[r-1]) 48 printLine(r, lines[r-1])
42 # print source line containing error: 49 # print source line containing error:
43 printLine(e.row, lines[e.row-1]) 50 printLine(ro, lines[ro-1])
44 print(' '*(len(str(e.row)+':')+e.col-1) + '^ Error: {0}'.format(e.msg)) 51 print(' '*(len(str(ro)+':')+co-1) + '^ Error: {0}'.format(e.msg))
45 # print trailing source line: 52 # print trailing source line:
46 for r in range(e.row+1, afterrow+1): 53 for r in range(ro+1, afterrow+1):
47 printLine(r, lines[r-1]) 54 printLine(r, lines[r-1])
55
56 class Diagnostics:
57 def __init__(self):
58 self.diags = []
59 def diag(self, d):
60 self.diags.append(d)
61