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()
|
163
|
64 elif self.Peak == 'const':
|
|
65 self.parseConstDef()
|
149
|
66 else:
|
|
67 self.Error('Expected function or variable')
|
148
|
68
|
|
69 def parseDesignator(self):
|
|
70 """ A designator designates an object """
|
|
71 name = self.Consume('ID')
|
150
|
72 return self.sema.actOnDesignator(name.val, name.loc)
|
148
|
73
|
|
74 # Type system
|
|
75 def parseType(self):
|
|
76 d = self.parseDesignator()
|
|
77 return d
|
|
78
|
|
79 # Variable declarations:
|
149
|
80 def parseVarDef(self):
|
148
|
81 self.Consume('var')
|
149
|
82 t = self.parseType()
|
|
83 def parseVar():
|
|
84 name = self.Consume('ID')
|
|
85 ival = None
|
|
86 if self.hasConsumed('='):
|
|
87 ival = self.parseExpression()
|
|
88 self.sema.actOnVarDef(name.val, name.loc, t, ival)
|
|
89 parseVar()
|
|
90 while self.hasConsumed(','):
|
|
91 parseVar()
|
157
|
92 self.Consume(';')
|
148
|
93
|
163
|
94 def parseConstDef(self):
|
|
95 self.Consume('const')
|
|
96 t = self.parseType()
|
|
97 def parseConst():
|
|
98 name = self.Consume('ID')
|
|
99 self.Consume('=')
|
|
100 val = self.parseExpression()
|
|
101 self.sema.actOnConstDef(name.val, name.loc, t, val)
|
|
102 parseConst()
|
|
103 while self.hasConsumed(','):
|
|
104 parseConst()
|
|
105 self.Consume(';')
|
|
106
|
148
|
107 # Procedures
|
149
|
108 def parseFunctionDefinition(self):
|
148
|
109 self.Consume('function')
|
|
110 returntype = self.parseType()
|
149
|
111 pname = self.Consume('ID')
|
|
112 self.sema.actOnFuncDef1(pname.val, pname.loc)
|
148
|
113 self.Consume('(')
|
|
114 parameters = []
|
|
115 if not self.hasConsumed(')'):
|
150
|
116 def parseParameter():
|
148
|
117 typ = self.parseType()
|
|
118 name = self.Consume('ID')
|
150
|
119 parameters.append(self.sema.actOnParameter(name.val, name.loc, typ))
|
|
120 parseParameter()
|
|
121 while self.hasConsumed(','):
|
|
122 parseParameter()
|
148
|
123 self.Consume(')')
|
|
124 body = self.parseCompoundStatement()
|
149
|
125 self.sema.actOnFuncDef2(parameters, returntype, body)
|
148
|
126
|
|
127 # Statements:
|
|
128 def parseAssignment(self, lval):
|
165
|
129 lval = self.sema.actOnVariableUse(lval, lval.loc)
|
164
|
130 loc = self.Consume('=').loc
|
148
|
131 rval = self.parseExpression()
|
157
|
132 self.Consume(';')
|
164
|
133 return self.sema.actOnAssignment(lval, rval, loc)
|
148
|
134
|
|
135 def parseProcedureCall(self, procedure):
|
|
136 self.Consume('(')
|
|
137 args = []
|
|
138 if not self.hasConsumed(')'):
|
|
139 args.append(self.parseExpression())
|
|
140 while self.hasConsumed(','):
|
|
141 args.append(self.parseExpression())
|
|
142 self.Consume(')')
|
155
|
143 return astnodes.ProcedureCall(procedure, args)
|
148
|
144
|
|
145 def parseIfStatement(self):
|
165
|
146 loc = self.Consume('if').loc
|
148
|
147 self.Consume('(')
|
|
148 condition = self.parseExpression()
|
|
149 self.Consume(')')
|
149
|
150 yes = self.parseCompoundStatement()
|
148
|
151 if self.hasConsumed('else'):
|
149
|
152 no = self.parseCompoundStatement()
|
165
|
153 else:
|
|
154 no = astnodes.EmptyStatement()
|
|
155 return self.sema.actOnIfStatement(condition, yes, no, loc)
|
148
|
156
|
|
157 def parseWhileStatement(self):
|
|
158 self.Consume('while')
|
|
159 self.Consume('(')
|
|
160 condition = self.parseExpression()
|
|
161 self.Consume(')')
|
149
|
162 statements = self.parseCompoundStatement()
|
|
163 return astnodes.WhileStatement(condition, statements)
|
|
164
|
148
|
165 def parseReturnStatement(self):
|
|
166 self.Consume('return')
|
|
167 expr = self.parseExpression()
|
157
|
168 self.Consume(';')
|
149
|
169 return astnodes.ReturnStatement(expr)
|
148
|
170
|
|
171 def parseCompoundStatement(self):
|
149
|
172 self.Consume('{')
|
157
|
173 statements = []
|
|
174 while not self.hasConsumed('}'):
|
148
|
175 statements.append(self.parseStatement())
|
149
|
176 return astnodes.CompoundStatement(statements)
|
148
|
177
|
|
178 def parseStatement(self):
|
|
179 # Determine statement type based on the pending token:
|
|
180 if self.Peak == 'if':
|
|
181 return self.parseIfStatement()
|
|
182 elif self.Peak == 'while':
|
|
183 return self.parseWhileStatement()
|
|
184 elif self.Peak == '{':
|
|
185 return self.parseCompoundStatement()
|
158
|
186 elif self.hasConsumed(';'):
|
155
|
187 return astnodes.EmptyStatement()
|
148
|
188 elif self.Peak == 'var':
|
158
|
189 self.parseVarDef()
|
|
190 return astnodes.EmptyStatement()
|
148
|
191 elif self.Peak == 'return':
|
|
192 return self.parseReturnStatement()
|
|
193 elif self.Peak == 'ID':
|
|
194 designator = self.parseDesignator()
|
|
195 if self.Peak == '(':
|
|
196 return self.parseProcedureCall(designator)
|
|
197 elif self.Peak == '=':
|
|
198 return self.parseAssignment(designator)
|
|
199 self.Error('Unable to determine statement')
|
|
200
|
|
201 # Parsing expressions:
|
|
202 def parseExpression(self):
|
|
203 return self.parseBinopRhs(self.parsePrimary(), 0)
|
|
204 def parsePrimary(self):
|
|
205 if self.hasConsumed('('):
|
|
206 e = self.parseExpression()
|
|
207 self.Consume(')')
|
|
208 return e
|
|
209 elif self.Peak == 'NUMBER':
|
|
210 val = self.Consume('NUMBER')
|
149
|
211 return self.sema.actOnNumber(val.val, val.loc)
|
163
|
212 elif self.Peak == 'REAL':
|
|
213 val = self.Consume('REAL')
|
|
214 return self.sema.actOnNumber(val.val, val.loc)
|
148
|
215 elif self.Peak == 'ID':
|
|
216 d = self.parseDesignator()
|
155
|
217 if self.Peak == '(':
|
|
218 return self.parseProcedureCall(d)
|
|
219 else:
|
165
|
220 return self.sema.actOnVariableUse(d, d.loc)
|
148
|
221 self.Error('Expected NUM, ID or (expr), got {0}'.format(self.Peak))
|
|
222
|
|
223 def parseBinopRhs(self, lhs, min_prec):
|
|
224 while self.PeakPrec >= min_prec:
|
|
225 op_prec = self.PeakPrec
|
|
226 op = self.Consume(self.Peak)
|
|
227 rhs = self.parsePrimary()
|
|
228 while self.PeakPrec > op_prec:
|
|
229 rhs = self.parseBinopRhs(rhs, self.PeakPrec)
|
149
|
230 lhs = self.sema.actOnBinop(lhs, op.typ, rhs, op.loc)
|
148
|
231 return lhs
|
|
232
|