view python/c3/typecheck.py @ 165:598d3888a11c

Added front class and fided AST view
author Windel Bouwman
date Fri, 22 Mar 2013 15:12:38 +0100
parents e023d3ce1d63
children da0087b82fbe
line wrap: on
line source

from .astnodes import *
from .scope import *
from .visitor import Visitor

def equalTypes(a, b):
   """ Compare types a and b for equality. Not equal until proven otherwise. """
   if type(a) is type(b):
      if type(a) is BaseType:
         return a.name == b.name
   return False

class TypeChecker:
   def __init__(self, diag):
      self.diag = diag
      self.visitor = Visitor(self.precheck, self.check2)
   def checkPackage(self, pkg):
      self.visitor.visit(pkg)
   def precheck(self, sym):
      pass
   def check2(self, sym):
      if type(sym) is Function:
         pass
      elif type(sym) in [IfStatement, WhileStatement]:
         if not equalTypes(sym.condition.typ, boolType):
            self.diag.error('Condition must be a boolean expression', sym.condition.loc)
      elif type(sym) is Assignment:
         if not equalTypes(sym.lval.typ, sym.rval.typ):
            self.diag.error('Cannot assign {0} to {1}'.format(sym.rval.typ, sym.lval.typ), sym.loc)
      elif type(sym) is ReturnStatement:
         pass
      elif type(sym) is ProcedureCall:
         # Check arguments:

         # determine return type:
         sym.typ = sym.proc.typ.returntype
      elif type(sym) is VariableUse:
         if sym.target:
            sym.typ = sym.target.typ
         else:
            sym.typ = intType
      elif type(sym) is Literal:
         if type(sym.val) is int:
            sym.typ = intType
         elif type(sym.val) is float:
            sym.typ = doubleType
         else:
            self.diag.error('Unknown literal type', sym.loc)
      elif type(sym) is Binop:
         if sym.op in ['+', '-', '*', '/']:
            if equalTypes(sym.a.typ, sym.b.typ):
               sym.typ = sym.a.typ
            else:
               # assume void here? TODO: throw exception!
               sym.typ = intType
               self.diag.error('Types unequal', sym.loc)
         elif sym.op in ['>', '<']:
            sym.typ = boolType
            if not equalTypes(sym.a.typ, sym.b.typ):
               self.diag.error('Types unequal', sym.loc)
         else:
            sym.typ = voidType
            print('unknown binop', sym.op)
      elif type(sym) is Variable:
         # check initial value type:
         # TODO
         pass
      elif type(sym) in [EmptyStatement, CompoundStatement, Package]:
         pass
      else:
         print('Unknown type check', sym)