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
|
150
|
23 elif type(sym) is IfStatement:
|
163
|
24 print(sym.condition)
|
|
25 if not equalTypes(sym.condition.typ, boolType):
|
|
26 self.diag.error('Condition must be a boolean expression', sym.condition.loc)
|
150
|
27 elif type(sym) is Assignment:
|
164
|
28 if not equalTypes(sym.lval.typ, sym.rval.typ):
|
|
29 self.diag.error('Cannot assign {0} to {1}'.format(sym.rval.typ, sym.lval.typ), sym.loc)
|
150
|
30 elif type(sym) is ReturnStatement:
|
163
|
31 pass
|
|
32 elif type(sym) is ProcedureCall:
|
|
33 # Check arguments:
|
|
34
|
|
35 # determine return type:
|
|
36 sym.typ = sym.proc.typ.returntype
|
|
37 elif type(sym) is VariableUse:
|
|
38 if sym.target:
|
|
39 sym.typ = sym.target.typ
|
|
40 else:
|
|
41 sym.typ = voidType
|
|
42 elif type(sym) is Literal:
|
|
43 if type(sym.val) is int:
|
|
44 sym.typ = intType
|
|
45 elif type(sym.val) is float:
|
|
46 sym.typ = doubleType
|
|
47 else:
|
|
48 self.diag.error('Unknown literal type', sym.loc)
|
150
|
49 elif type(sym) is Binop:
|
163
|
50 if sym.op in ['+', '-', '*', '/']:
|
|
51 if equalTypes(sym.a.typ, sym.b.typ):
|
|
52 sym.typ = sym.a.typ
|
|
53 else:
|
|
54 # assume void here?
|
|
55 sym.typ = voidType
|
|
56 self.diag.error('Types unequal', sym.loc)
|
|
57 elif sym.op in ['>', '<']:
|
|
58 if equalTypes(sym.a.typ, sym.b.typ):
|
|
59 sym.typ = boolType
|
|
60 else:
|
|
61 sym.typ = voidType
|
|
62 self.diag.error('Types unequal', sym.loc)
|
|
63 else:
|
|
64 sym.typ = voidType
|
|
65 print('unknown binop', sym.op)
|
|
66 else:
|
|
67 print('Unknown type check', sym)
|
150
|
68
|