163
|
1 from .visitor import Visitor
|
|
2 from .astnodes import *
|
215
|
3 from .scope import Scope, topScope
|
150
|
4
|
|
5 class Analyzer:
|
215
|
6 """
|
|
7 Context handling is done here.
|
|
8 Scope is attached to the correct modules.
|
|
9 This class checks names and references
|
|
10 """
|
|
11 def __init__(self, diag):
|
|
12 self.diag = diag
|
186
|
13
|
215
|
14 def analyzePackage(self, pkg):
|
186
|
15 self.ok = True
|
215
|
16 visitor = Visitor()
|
|
17 # Prepare top level scope:
|
|
18 self.curScope = topScope
|
|
19 visitor.visit(pkg, self.enterScope, self.quitScope)
|
|
20 del self.curScope
|
|
21 visitor.visit(pkg, self.findRefs)
|
|
22 visitor.visit(pkg, self.sanity)
|
186
|
23 return self.ok
|
215
|
24
|
|
25 def error(self, msg, loc=None):
|
|
26 self.ok = False
|
|
27 self.diag.error(msg, loc)
|
|
28
|
|
29 # Scope creation:
|
|
30 def addSymbol(self, sym):
|
|
31 if self.curScope.hasSymbol(sym.name):
|
|
32 self.error('Redefinition of {0}'.format(sym.name), sym.loc)
|
|
33 else:
|
|
34 self.curScope.addSymbol(sym)
|
|
35
|
|
36 def enterScope(self, sym):
|
|
37 # Distribute the scope:
|
|
38 sym.scope = self.curScope
|
|
39
|
|
40 # Add symbols to current scope:
|
|
41 if isinstance(sym, Symbol):
|
|
42 self.addSymbol(sym)
|
|
43
|
|
44 # Create subscope:
|
|
45 if type(sym) in [Package, Function]:
|
|
46 self.curScope = Scope(self.curScope)
|
217
|
47 sym.innerScope = self.curScope
|
215
|
48
|
|
49 def quitScope(self, sym):
|
|
50 # Pop out of scope:
|
|
51 if type(sym) in [Package, Function]:
|
|
52 self.curScope = self.curScope.parent
|
150
|
53
|
215
|
54 # Reference fixups:
|
|
55 def resolveDesignator(self, d, scope):
|
|
56 assert type(d) is Designator
|
|
57 assert type(scope) is Scope
|
|
58 if scope.hasSymbol(d.tname):
|
|
59 s = scope.getSymbol(d.tname)
|
|
60 if hasattr(s, 'addRef'):
|
|
61 # TODO: make this nicer
|
|
62 s.addRef(None)
|
|
63 return s
|
|
64 else:
|
|
65 self.ok = False
|
|
66 msg = 'Cannot resolve name {0}'.format(d.tname)
|
|
67 self.diag.error(msg, d.loc)
|
|
68
|
|
69 def findRefs(self, sym):
|
|
70 if type(sym) in [Variable, Constant]:
|
|
71 sym.typ = self.resolveDesignator(sym.typ, sym.scope)
|
|
72 elif type(sym) is VariableUse:
|
|
73 sym.target = self.resolveDesignator(sym.target, sym.scope)
|
|
74 elif type(sym) is FunctionCall:
|
|
75 sym.proc = self.resolveDesignator(sym.proc, sym.scope)
|
|
76 elif type(sym) is Function:
|
|
77 # Checkup function type:
|
|
78 ft = sym.typ
|
|
79 ft.returntype = self.resolveDesignator(ft.returntype, sym.scope)
|
|
80 ft.parametertypes = [self.resolveDesignator(pt, sym.scope) for pt in ft.parametertypes]
|
|
81
|
|
82 def sanity(self, sym):
|
|
83 if type(sym) is FunctionType:
|
|
84 pass
|
|
85 elif type(sym) is Function:
|
|
86 pass
|
|
87
|