148
|
1 from . import astnodes, lexer, semantics
|
152
|
2 from ppci import CompilerError
|
148
|
3
|
|
4 # binop precedence for expressions:
|
|
5 binopPrecs = {'or': 5, 'and': 10, \
|
|
6 '<': 20, '>': 20, '==': 20, '<=': 20, '>=': 20, '!=': 20, \
|
|
7 '+': 30, '-': 30, '*': 40, '/': 40 }
|
|
8
|
|
9 class Parser:
|
|
10 """ Parses sourcecode into an abstract syntax tree (AST) """
|
|
11 def __init__(self, sema, diag):
|
|
12 self.sema = sema
|
|
13 self.diag = diag
|
|
14 def parseSource(self, source):
|
|
15 self.initLex(source)
|
|
16 try:
|
|
17 self.parsePackage()
|
152
|
18 except CompilerError as e:
|
|
19 self.diag.addDiag(e)
|
148
|
20 def Error(self, msg):
|
152
|
21 raise CompilerError(msg, self.token.loc)
|
148
|
22 # Lexer helpers:
|
|
23 def Consume(self, typ):
|
|
24 if self.Peak == typ:
|
|
25 return self.NextToken()
|
|
26 else:
|
|
27 self.Error('Excected: "{0}", got "{1}"'.format(typ, self.Peak))
|
|
28 @property
|
|
29 def Peak(self):
|
|
30 return self.token.typ
|
|
31 @property
|
|
32 def PeakPrec(self):
|
149
|
33 if self.Peak in binopPrecs:
|
|
34 return binopPrecs[self.Peak]
|
|
35 return -1
|
148
|
36 def hasConsumed(self, typ):
|
|
37 if self.Peak == typ:
|
|
38 self.Consume(typ)
|
|
39 return True
|
|
40 return False
|
|
41 def NextToken(self):
|
|
42 t = self.token
|
150
|
43 if t.typ != 'END': self.token = self.tokens.__next__()
|
148
|
44 return t
|
|
45 def initLex(self, source):
|
|
46 self.tokens = lexer.tokenize(source) # Lexical stage
|
|
47 self.token = self.tokens.__next__()
|
|
48
|
|
49 def parsePackage(self):
|
|
50 self.Consume('package')
|
|
51 name = self.Consume('ID')
|
|
52 self.Consume(';')
|
|
53 self.sema.handlePackage(name.val, name.loc)
|
|
54 # TODO: parse uses
|
|
55 while self.Peak != 'END':
|
|
56 self.parseTopLevel()
|
|
57 self.Consume('END')
|
|
58
|
|
59 def parseTopLevel(self):
|
|
60 if self.Peak == 'function':
|
149
|
61 self.parseFunctionDefinition()
|
148
|
62 elif self.Peak == 'var':
|
149
|
63 self.parseVarDef()
|
|
64 else:
|
|
65 self.Error('Expected function or variable')
|
148
|
66
|
|
67 def parseDesignator(self):
|
|
68 """ A designator designates an object """
|
|
69 name = self.Consume('ID')
|
150
|
70 return self.sema.actOnDesignator(name.val, name.loc)
|
148
|
71
|
|
72 # Type system
|
|
73 def parseType(self):
|
|
74 d = self.parseDesignator()
|
|
75 return d
|
|
76
|
|
77 # Variable declarations:
|
149
|
78 def parseVarDef(self):
|
148
|
79 self.Consume('var')
|
149
|
80 t = self.parseType()
|
|
81 def parseVar():
|
|
82 name = self.Consume('ID')
|
|
83 ival = None
|
|
84 if self.hasConsumed('='):
|
|
85 ival = self.parseExpression()
|
|
86 self.sema.actOnVarDef(name.val, name.loc, t, ival)
|
|
87 parseVar()
|
|
88 while self.hasConsumed(','):
|
|
89 parseVar()
|
157
|
90 self.Consume(';')
|
148
|
91
|
|
92 # Procedures
|
149
|
93 def parseFunctionDefinition(self):
|
148
|
94 self.Consume('function')
|
|
95 returntype = self.parseType()
|
149
|
96 pname = self.Consume('ID')
|
|
97 self.sema.actOnFuncDef1(pname.val, pname.loc)
|
148
|
98 self.Consume('(')
|
|
99 parameters = []
|
|
100 if not self.hasConsumed(')'):
|
150
|
101 def parseParameter():
|
148
|
102 typ = self.parseType()
|
|
103 name = self.Consume('ID')
|
150
|
104 parameters.append(self.sema.actOnParameter(name.val, name.loc, typ))
|
|
105 parseParameter()
|
|
106 while self.hasConsumed(','):
|
|
107 parseParameter()
|
148
|
108 self.Consume(')')
|
|
109 body = self.parseCompoundStatement()
|
149
|
110 self.sema.actOnFuncDef2(parameters, returntype, body)
|
148
|
111
|
|
112 # Statements:
|
|
113 def parseAssignment(self, lval):
|
150
|
114 lval = astnodes.VariableUse(lval)
|
148
|
115 self.Consume('=')
|
|
116 rval = self.parseExpression()
|
157
|
117 self.Consume(';')
|
148
|
118 return astnodes.Assignment(lval, rval)
|
|
119
|
|
120 def parseProcedureCall(self, procedure):
|
|
121 self.Consume('(')
|
|
122 args = []
|
|
123 if not self.hasConsumed(')'):
|
|
124 args.append(self.parseExpression())
|
|
125 while self.hasConsumed(','):
|
|
126 args.append(self.parseExpression())
|
|
127 self.Consume(')')
|
155
|
128 return astnodes.ProcedureCall(procedure, args)
|
148
|
129
|
|
130 def parseIfStatement(self):
|
|
131 self.Consume('if')
|
|
132 self.Consume('(')
|
|
133 condition = self.parseExpression()
|
|
134 self.Consume(')')
|
149
|
135 yes = self.parseCompoundStatement()
|
148
|
136 if self.hasConsumed('else'):
|
149
|
137 no = self.parseCompoundStatement()
|
|
138 return astnodes.IfStatement(condition, yes, no)
|
|
139 return astnodes.IfStatement(condition, yes)
|
148
|
140
|
|
141 def parseWhileStatement(self):
|
|
142 self.Consume('while')
|
|
143 self.Consume('(')
|
|
144 condition = self.parseExpression()
|
|
145 self.Consume(')')
|
149
|
146 statements = self.parseCompoundStatement()
|
|
147 return astnodes.WhileStatement(condition, statements)
|
|
148
|
148
|
149 def parseReturnStatement(self):
|
|
150 self.Consume('return')
|
|
151 expr = self.parseExpression()
|
157
|
152 self.Consume(';')
|
149
|
153 return astnodes.ReturnStatement(expr)
|
148
|
154
|
|
155 def parseCompoundStatement(self):
|
149
|
156 self.Consume('{')
|
157
|
157 statements = []
|
|
158 while not self.hasConsumed('}'):
|
148
|
159 statements.append(self.parseStatement())
|
149
|
160 return astnodes.CompoundStatement(statements)
|
148
|
161
|
|
162 def parseStatement(self):
|
|
163 # Determine statement type based on the pending token:
|
|
164 if self.Peak == 'if':
|
|
165 return self.parseIfStatement()
|
|
166 elif self.Peak == 'while':
|
|
167 return self.parseWhileStatement()
|
|
168 elif self.Peak == '{':
|
|
169 return self.parseCompoundStatement()
|
155
|
170 elif self.Peak == ';':
|
157
|
171 self.Consume(';')
|
155
|
172 return astnodes.EmptyStatement()
|
148
|
173 elif self.Peak == 'var':
|
149
|
174 return self.parseVarDef()
|
148
|
175 elif self.Peak == 'return':
|
|
176 return self.parseReturnStatement()
|
|
177 elif self.Peak == 'ID':
|
|
178 designator = self.parseDesignator()
|
|
179 if self.Peak == '(':
|
|
180 return self.parseProcedureCall(designator)
|
|
181 elif self.Peak == '=':
|
|
182 return self.parseAssignment(designator)
|
|
183 self.Error('Unable to determine statement')
|
|
184
|
|
185 # Parsing expressions:
|
|
186 def parseExpression(self):
|
|
187 return self.parseBinopRhs(self.parsePrimary(), 0)
|
|
188 def parsePrimary(self):
|
|
189 if self.hasConsumed('('):
|
|
190 e = self.parseExpression()
|
|
191 self.Consume(')')
|
|
192 return e
|
|
193 elif self.Peak == 'NUMBER':
|
|
194 val = self.Consume('NUMBER')
|
149
|
195 return self.sema.actOnNumber(val.val, val.loc)
|
148
|
196 elif self.Peak == 'ID':
|
|
197 d = self.parseDesignator()
|
155
|
198 if self.Peak == '(':
|
|
199 return self.parseProcedureCall(d)
|
|
200 else:
|
|
201 return self.sema.actOnVariableUse(d)
|
148
|
202 self.Error('Expected NUM, ID or (expr), got {0}'.format(self.Peak))
|
|
203
|
|
204 def parseBinopRhs(self, lhs, min_prec):
|
|
205 while self.PeakPrec >= min_prec:
|
|
206 op_prec = self.PeakPrec
|
|
207 op = self.Consume(self.Peak)
|
|
208 rhs = self.parsePrimary()
|
|
209 while self.PeakPrec > op_prec:
|
|
210 rhs = self.parseBinopRhs(rhs, self.PeakPrec)
|
149
|
211 lhs = self.sema.actOnBinop(lhs, op.typ, rhs, op.loc)
|
148
|
212 return lhs
|
|
213
|