view python/ppci/errors.py @ 155:b28a11c01dbe

Simplified IR classes
author Windel Bouwman
date Sun, 03 Mar 2013 13:20:03 +0100
parents b73bc14a3aa3
children 0b5b2ee6b435
line wrap: on
line source

""" 
   Error handling routines 
   Diagnostic utils
"""

class CompilerError(Exception):
  def __init__(self, msg, loc):
    self.msg = msg
    self.loc = loc
  def __repr__(self):
     return 'Compilererror {0} at {1}'.format(self.msg, self.loc)

def printError(source, e):
     def printLine(row, txt):
        print(str(row)+':'+txt)
     if e.loc.row == 0:
        print('Error: {0}'.format(e.msg))
     else:
        lines = source.split('\n')
        ro, co = e.loc.row, e.loc.col
        prerow = ro - 2
        if prerow < 1:
           prerow = 1
        afterrow = ro + 3
        if afterrow > len(lines):
           afterrow = len(lines)

        # print preceding source lines:
        for r in range(prerow, ro):
           printLine(r, lines[r-1])
        # print source line containing error:
        printLine(ro, lines[ro-1])
        print(' '*(len(str(ro)+':')+co-1) + '^ Error: {0}'.format(e.msg))
        # print trailing source line:
        for r in range(ro+1, afterrow+1):
          printLine(r, lines[r-1])

class DiagnosticsManager:
   def __init__(self):
      self.diags = []
   def addDiag(self, d):
      self.diags.append(d)
   def error(self, msg, loc):
      self.addDiag(CompilerError(msg, loc))