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 self.Consume(';')
|
|
65 else:
|
|
66 self.Error('Expected function or variable')
|
148
|
67
|
|
68 def parseDesignator(self):
|
|
69 """ A designator designates an object """
|
|
70 name = self.Consume('ID')
|
150
|
71 return self.sema.actOnDesignator(name.val, name.loc)
|
148
|
72
|
|
73 # Type system
|
|
74 def parseType(self):
|
|
75 d = self.parseDesignator()
|
|
76 return d
|
|
77
|
|
78 # Variable declarations:
|
149
|
79 def parseVarDef(self):
|
148
|
80 self.Consume('var')
|
149
|
81 t = self.parseType()
|
|
82 def parseVar():
|
|
83 name = self.Consume('ID')
|
|
84 ival = None
|
|
85 if self.hasConsumed('='):
|
|
86 ival = self.parseExpression()
|
|
87 self.sema.actOnVarDef(name.val, name.loc, t, ival)
|
|
88 parseVar()
|
|
89 while self.hasConsumed(','):
|
|
90 parseVar()
|
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()
|
|
117 return astnodes.Assignment(lval, rval)
|
|
118
|
|
119 def parseProcedureCall(self, procedure):
|
|
120 self.Consume('(')
|
|
121 args = []
|
|
122 if not self.hasConsumed(')'):
|
|
123 args.append(self.parseExpression())
|
|
124 while self.hasConsumed(','):
|
|
125 args.append(self.parseExpression())
|
|
126 self.Consume(')')
|
155
|
127 return astnodes.ProcedureCall(procedure, args)
|
148
|
128
|
|
129 def parseIfStatement(self):
|
|
130 self.Consume('if')
|
|
131 self.Consume('(')
|
|
132 condition = self.parseExpression()
|
|
133 self.Consume(')')
|
149
|
134 yes = self.parseCompoundStatement()
|
148
|
135 if self.hasConsumed('else'):
|
149
|
136 no = self.parseCompoundStatement()
|
|
137 return astnodes.IfStatement(condition, yes, no)
|
|
138 return astnodes.IfStatement(condition, yes)
|
148
|
139
|
|
140 def parseWhileStatement(self):
|
|
141 self.Consume('while')
|
|
142 self.Consume('(')
|
|
143 condition = self.parseExpression()
|
|
144 self.Consume(')')
|
149
|
145 statements = self.parseCompoundStatement()
|
|
146 return astnodes.WhileStatement(condition, statements)
|
|
147
|
148
|
148 def parseReturnStatement(self):
|
|
149 self.Consume('return')
|
|
150 expr = self.parseExpression()
|
149
|
151 return astnodes.ReturnStatement(expr)
|
148
|
152
|
|
153 def parseCompoundStatement(self):
|
149
|
154 self.Consume('{')
|
|
155 statements = [self.parseStatement()]
|
|
156 while self.hasConsumed(';'):
|
155
|
157 if self.Peak == '}': break # Permit last ';'
|
148
|
158 statements.append(self.parseStatement())
|
149
|
159 self.Consume('}')
|
|
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 == ';':
|
|
171 return astnodes.EmptyStatement()
|
148
|
172 elif self.Peak == 'var':
|
149
|
173 return self.parseVarDef()
|
148
|
174 elif self.Peak == 'return':
|
|
175 return self.parseReturnStatement()
|
|
176 elif self.Peak == 'ID':
|
|
177 designator = self.parseDesignator()
|
|
178 if self.Peak == '(':
|
|
179 return self.parseProcedureCall(designator)
|
|
180 elif self.Peak == '=':
|
|
181 return self.parseAssignment(designator)
|
|
182 self.Error('Unable to determine statement')
|
|
183
|
|
184 # Parsing expressions:
|
|
185 def parseExpression(self):
|
|
186 return self.parseBinopRhs(self.parsePrimary(), 0)
|
|
187 def parsePrimary(self):
|
|
188 if self.hasConsumed('('):
|
|
189 e = self.parseExpression()
|
|
190 self.Consume(')')
|
|
191 return e
|
|
192 elif self.Peak == 'NUMBER':
|
|
193 val = self.Consume('NUMBER')
|
149
|
194 return self.sema.actOnNumber(val.val, val.loc)
|
148
|
195 elif self.Peak == 'ID':
|
|
196 d = self.parseDesignator()
|
155
|
197 if self.Peak == '(':
|
|
198 return self.parseProcedureCall(d)
|
|
199 else:
|
|
200 return self.sema.actOnVariableUse(d)
|
148
|
201 self.Error('Expected NUM, ID or (expr), got {0}'.format(self.Peak))
|
|
202
|
|
203 def parseBinopRhs(self, lhs, min_prec):
|
|
204 while self.PeakPrec >= min_prec:
|
|
205 op_prec = self.PeakPrec
|
|
206 op = self.Consume(self.Peak)
|
|
207 rhs = self.parsePrimary()
|
|
208 while self.PeakPrec > op_prec:
|
|
209 rhs = self.parseBinopRhs(rhs, self.PeakPrec)
|
149
|
210 lhs = self.sema.actOnBinop(lhs, op.typ, rhs, op.loc)
|
148
|
211 return lhs
|
|
212
|