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):
|
158
|
129 lval = self.sema.actOnVariableUse(lval)
|
148
|
130 self.Consume('=')
|
|
131 rval = self.parseExpression()
|
157
|
132 self.Consume(';')
|
148
|
133 return astnodes.Assignment(lval, rval)
|
|
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):
|
|
146 self.Consume('if')
|
|
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()
|
|
153 return astnodes.IfStatement(condition, yes, no)
|
158
|
154 return astnodes.IfStatement(condition, yes, astnodes.EmptyStatement())
|
148
|
155
|
|
156 def parseWhileStatement(self):
|
|
157 self.Consume('while')
|
|
158 self.Consume('(')
|
|
159 condition = self.parseExpression()
|
|
160 self.Consume(')')
|
149
|
161 statements = self.parseCompoundStatement()
|
|
162 return astnodes.WhileStatement(condition, statements)
|
|
163
|
148
|
164 def parseReturnStatement(self):
|
|
165 self.Consume('return')
|
|
166 expr = self.parseExpression()
|
157
|
167 self.Consume(';')
|
149
|
168 return astnodes.ReturnStatement(expr)
|
148
|
169
|
|
170 def parseCompoundStatement(self):
|
149
|
171 self.Consume('{')
|
157
|
172 statements = []
|
|
173 while not self.hasConsumed('}'):
|
148
|
174 statements.append(self.parseStatement())
|
149
|
175 return astnodes.CompoundStatement(statements)
|
148
|
176
|
|
177 def parseStatement(self):
|
|
178 # Determine statement type based on the pending token:
|
|
179 if self.Peak == 'if':
|
|
180 return self.parseIfStatement()
|
|
181 elif self.Peak == 'while':
|
|
182 return self.parseWhileStatement()
|
|
183 elif self.Peak == '{':
|
|
184 return self.parseCompoundStatement()
|
158
|
185 elif self.hasConsumed(';'):
|
155
|
186 return astnodes.EmptyStatement()
|
148
|
187 elif self.Peak == 'var':
|
158
|
188 self.parseVarDef()
|
|
189 return astnodes.EmptyStatement()
|
148
|
190 elif self.Peak == 'return':
|
|
191 return self.parseReturnStatement()
|
|
192 elif self.Peak == 'ID':
|
|
193 designator = self.parseDesignator()
|
|
194 if self.Peak == '(':
|
|
195 return self.parseProcedureCall(designator)
|
|
196 elif self.Peak == '=':
|
|
197 return self.parseAssignment(designator)
|
|
198 self.Error('Unable to determine statement')
|
|
199
|
|
200 # Parsing expressions:
|
|
201 def parseExpression(self):
|
|
202 return self.parseBinopRhs(self.parsePrimary(), 0)
|
|
203 def parsePrimary(self):
|
|
204 if self.hasConsumed('('):
|
|
205 e = self.parseExpression()
|
|
206 self.Consume(')')
|
|
207 return e
|
|
208 elif self.Peak == 'NUMBER':
|
|
209 val = self.Consume('NUMBER')
|
149
|
210 return self.sema.actOnNumber(val.val, val.loc)
|
163
|
211 elif self.Peak == 'REAL':
|
|
212 val = self.Consume('REAL')
|
|
213 return self.sema.actOnNumber(val.val, val.loc)
|
148
|
214 elif self.Peak == 'ID':
|
|
215 d = self.parseDesignator()
|
155
|
216 if self.Peak == '(':
|
|
217 return self.parseProcedureCall(d)
|
|
218 else:
|
|
219 return self.sema.actOnVariableUse(d)
|
148
|
220 self.Error('Expected NUM, ID or (expr), got {0}'.format(self.Peak))
|
|
221
|
|
222 def parseBinopRhs(self, lhs, min_prec):
|
|
223 while self.PeakPrec >= min_prec:
|
|
224 op_prec = self.PeakPrec
|
|
225 op = self.Consume(self.Peak)
|
|
226 rhs = self.parsePrimary()
|
|
227 while self.PeakPrec > op_prec:
|
|
228 rhs = self.parseBinopRhs(rhs, self.PeakPrec)
|
149
|
229 lhs = self.sema.actOnBinop(lhs, op.typ, rhs, op.loc)
|
148
|
230 return lhs
|
|
231
|