163
|
1 from .astnodes import *
|
|
2 from .scope import *
|
|
3 from .visitor import Visitor
|
|
4
|
|
5 def equalTypes(a, b):
|
|
6 """ Compare types a and b for equality. Not equal until proven otherwise. """
|
|
7 if type(a) is type(b):
|
|
8 if type(a) is BaseType:
|
|
9 return a.name == b.name
|
|
10 return False
|
150
|
11
|
|
12 class TypeChecker:
|
|
13 def __init__(self, diag):
|
|
14 self.diag = diag
|
163
|
15 self.visitor = Visitor(self.precheck, self.check2)
|
150
|
16 def checkPackage(self, pkg):
|
163
|
17 self.visitor.visit(pkg)
|
|
18 def precheck(self, sym):
|
|
19 pass
|
|
20 def check2(self, sym):
|
|
21 if type(sym) is Function:
|
|
22 pass
|
165
|
23 elif type(sym) in [IfStatement, WhileStatement]:
|
163
|
24 if not equalTypes(sym.condition.typ, boolType):
|
|
25 self.diag.error('Condition must be a boolean expression', sym.condition.loc)
|
150
|
26 elif type(sym) is Assignment:
|
164
|
27 if not equalTypes(sym.lval.typ, sym.rval.typ):
|
|
28 self.diag.error('Cannot assign {0} to {1}'.format(sym.rval.typ, sym.lval.typ), sym.loc)
|
150
|
29 elif type(sym) is ReturnStatement:
|
163
|
30 pass
|
|
31 elif type(sym) is ProcedureCall:
|
|
32 # Check arguments:
|
|
33
|
|
34 # determine return type:
|
|
35 sym.typ = sym.proc.typ.returntype
|
|
36 elif type(sym) is VariableUse:
|
|
37 if sym.target:
|
|
38 sym.typ = sym.target.typ
|
|
39 else:
|
165
|
40 sym.typ = intType
|
163
|
41 elif type(sym) is Literal:
|
|
42 if type(sym.val) is int:
|
|
43 sym.typ = intType
|
|
44 elif type(sym.val) is float:
|
|
45 sym.typ = doubleType
|
|
46 else:
|
|
47 self.diag.error('Unknown literal type', sym.loc)
|
150
|
48 elif type(sym) is Binop:
|
163
|
49 if sym.op in ['+', '-', '*', '/']:
|
|
50 if equalTypes(sym.a.typ, sym.b.typ):
|
|
51 sym.typ = sym.a.typ
|
|
52 else:
|
165
|
53 # assume void here? TODO: throw exception!
|
|
54 sym.typ = intType
|
163
|
55 self.diag.error('Types unequal', sym.loc)
|
|
56 elif sym.op in ['>', '<']:
|
165
|
57 sym.typ = boolType
|
|
58 if not equalTypes(sym.a.typ, sym.b.typ):
|
163
|
59 self.diag.error('Types unequal', sym.loc)
|
|
60 else:
|
|
61 sym.typ = voidType
|
|
62 print('unknown binop', sym.op)
|
165
|
63 elif type(sym) is Variable:
|
|
64 # check initial value type:
|
|
65 # TODO
|
|
66 pass
|
|
67 elif type(sym) in [EmptyStatement, CompoundStatement, Package]:
|
|
68 pass
|
163
|
69 else:
|
|
70 print('Unknown type check', sym)
|
150
|
71
|