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)
|
|
47
|
|
48 def quitScope(self, sym):
|
|
49 # Pop out of scope:
|
|
50 if type(sym) in [Package, Function]:
|
|
51 self.curScope = self.curScope.parent
|
150
|
52
|
215
|
53 # Reference fixups:
|
|
54 def resolveDesignator(self, d, scope):
|
|
55 assert type(d) is Designator
|
|
56 assert type(scope) is Scope
|
|
57 if scope.hasSymbol(d.tname):
|
|
58 s = scope.getSymbol(d.tname)
|
|
59 if hasattr(s, 'addRef'):
|
|
60 # TODO: make this nicer
|
|
61 s.addRef(None)
|
|
62 return s
|
|
63 else:
|
|
64 self.ok = False
|
|
65 msg = 'Cannot resolve name {0}'.format(d.tname)
|
|
66 self.diag.error(msg, d.loc)
|
|
67
|
|
68 def findRefs(self, sym):
|
|
69 if type(sym) in [Variable, Constant]:
|
|
70 sym.typ = self.resolveDesignator(sym.typ, sym.scope)
|
|
71 elif type(sym) is VariableUse:
|
|
72 sym.target = self.resolveDesignator(sym.target, sym.scope)
|
|
73 elif type(sym) is FunctionCall:
|
|
74 sym.proc = self.resolveDesignator(sym.proc, sym.scope)
|
|
75 elif type(sym) is Function:
|
|
76 # Checkup function type:
|
|
77 ft = sym.typ
|
|
78 ft.returntype = self.resolveDesignator(ft.returntype, sym.scope)
|
|
79 ft.parametertypes = [self.resolveDesignator(pt, sym.scope) for pt in ft.parametertypes]
|
|
80
|
|
81 def sanity(self, sym):
|
|
82 if type(sym) is FunctionType:
|
|
83 pass
|
|
84 elif type(sym) is Function:
|
|
85 pass
|
|
86
|