148
|
1 from . import astnodes, lexer, semantics
|
|
2 from ppci.errors import CompilerException, SourceLocation
|
|
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()
|
|
18 except CompilerException as e:
|
|
19 self.diag.diag(e)
|
|
20 def Error(self, msg):
|
|
21 raise CompilerException(msg, self.token.loc)
|
|
22 def skipToSemiCol(self):
|
|
23 while not (self.Peak == ';' or self.Peak == 'END'):
|
|
24 self.NextToken()
|
|
25 # Lexer helpers:
|
|
26 def Consume(self, typ):
|
|
27 if self.Peak == typ:
|
|
28 return self.NextToken()
|
|
29 else:
|
|
30 self.Error('Excected: "{0}", got "{1}"'.format(typ, self.Peak))
|
|
31 @property
|
|
32 def Peak(self):
|
|
33 return self.token.typ
|
|
34 @property
|
|
35 def PeakPrec(self):
|
149
|
36 if self.Peak in binopPrecs:
|
|
37 return binopPrecs[self.Peak]
|
|
38 return -1
|
148
|
39 def hasConsumed(self, typ):
|
|
40 if self.Peak == typ:
|
|
41 self.Consume(typ)
|
|
42 return True
|
|
43 return False
|
|
44 def NextToken(self):
|
|
45 t = self.token
|
|
46 if t.typ != 'END':
|
|
47 self.token = self.tokens.__next__()
|
|
48 return t
|
|
49 def initLex(self, source):
|
|
50 self.tokens = lexer.tokenize(source) # Lexical stage
|
|
51 self.token = self.tokens.__next__()
|
|
52
|
|
53 def parsePackage(self):
|
|
54 self.Consume('package')
|
|
55 name = self.Consume('ID')
|
|
56 self.Consume(';')
|
|
57 self.sema.handlePackage(name.val, name.loc)
|
|
58 # TODO: parse uses
|
|
59 while self.Peak != 'END':
|
|
60 self.parseTopLevel()
|
|
61 self.Consume('END')
|
|
62
|
|
63 def parseTopLevel(self):
|
|
64 if self.Peak == 'function':
|
149
|
65 self.parseFunctionDefinition()
|
148
|
66 elif self.Peak == 'var':
|
149
|
67 self.parseVarDef()
|
|
68 self.Consume(';')
|
|
69 else:
|
|
70 self.Error('Expected function or variable')
|
148
|
71
|
|
72 def parseDesignator(self):
|
|
73 """ A designator designates an object """
|
|
74 name = self.Consume('ID')
|
149
|
75 return name.val
|
148
|
76
|
|
77 # Type system
|
|
78 def parseType(self):
|
|
79 d = self.parseDesignator()
|
|
80 return d
|
|
81
|
|
82 # Variable declarations:
|
149
|
83 def parseVarDef(self):
|
148
|
84 self.Consume('var')
|
149
|
85 t = self.parseType()
|
|
86 def parseVar():
|
|
87 name = self.Consume('ID')
|
|
88 ival = None
|
|
89 if self.hasConsumed('='):
|
|
90 ival = self.parseExpression()
|
|
91 self.sema.actOnVarDef(name.val, name.loc, t, ival)
|
|
92 parseVar()
|
|
93 while self.hasConsumed(','):
|
|
94 parseVar()
|
148
|
95
|
|
96 # Procedures
|
149
|
97 def parseFunctionDefinition(self):
|
148
|
98 self.Consume('function')
|
|
99 returntype = self.parseType()
|
149
|
100 pname = self.Consume('ID')
|
|
101 self.sema.actOnFuncDef1(pname.val, pname.loc)
|
148
|
102 self.Consume('(')
|
|
103 parameters = []
|
|
104 if not self.hasConsumed(')'):
|
|
105 typ = self.parseType()
|
|
106 name = self.Consume('ID')
|
|
107 parameters.append(astnodes.Parameter(name, typ))
|
|
108 while self.hasConsumed(','):
|
|
109 typ = self.parseType()
|
|
110 name = self.Consume('ID')
|
|
111 parameters.append(astnodes.Parameter(name, typ))
|
|
112 self.Consume(')')
|
|
113 body = self.parseCompoundStatement()
|
149
|
114 self.sema.actOnFuncDef2(parameters, returntype, body)
|
148
|
115
|
|
116 # Statements:
|
|
117 def parseAssignment(self, lval):
|
|
118 self.Consume('=')
|
|
119 rval = self.parseExpression()
|
|
120 return astnodes.Assignment(lval, rval)
|
|
121
|
|
122 def parseProcedureCall(self, procedure):
|
|
123 self.Consume('(')
|
|
124 args = []
|
|
125 if not self.hasConsumed(')'):
|
|
126 args.append(self.parseExpression())
|
|
127 while self.hasConsumed(','):
|
|
128 args.append(self.parseExpression())
|
|
129 self.Consume(')')
|
|
130 return ProcedureCall(procedure, args)
|
|
131
|
|
132 def parseIfStatement(self):
|
|
133 self.Consume('if')
|
|
134 self.Consume('(')
|
|
135 condition = self.parseExpression()
|
|
136 self.Consume(')')
|
149
|
137 yes = self.parseCompoundStatement()
|
148
|
138 if self.hasConsumed('else'):
|
149
|
139 no = self.parseCompoundStatement()
|
|
140 return astnodes.IfStatement(condition, yes, no)
|
|
141 return astnodes.IfStatement(condition, yes)
|
148
|
142
|
|
143 def parseWhileStatement(self):
|
|
144 self.Consume('while')
|
|
145 self.Consume('(')
|
|
146 condition = self.parseExpression()
|
|
147 self.Consume(')')
|
149
|
148 statements = self.parseCompoundStatement()
|
|
149 return astnodes.WhileStatement(condition, statements)
|
|
150
|
148
|
151 def parseReturnStatement(self):
|
|
152 self.Consume('return')
|
|
153 expr = self.parseExpression()
|
149
|
154 return astnodes.ReturnStatement(expr)
|
148
|
155
|
|
156 def parseCompoundStatement(self):
|
149
|
157 self.Consume('{')
|
|
158 statements = [self.parseStatement()]
|
|
159 while self.hasConsumed(';'):
|
148
|
160 statements.append(self.parseStatement())
|
149
|
161 self.Consume('}')
|
|
162 return astnodes.CompoundStatement(statements)
|
148
|
163
|
|
164 def parseStatement(self):
|
|
165 # Determine statement type based on the pending token:
|
|
166 if self.Peak == 'if':
|
|
167 return self.parseIfStatement()
|
|
168 elif self.Peak == 'while':
|
|
169 return self.parseWhileStatement()
|
|
170 elif self.Peak == '{':
|
|
171 return self.parseCompoundStatement()
|
|
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()
|
|
197 return d
|
|
198 self.Error('Expected NUM, ID or (expr), got {0}'.format(self.Peak))
|
|
199
|
|
200 def parseBinopRhs(self, lhs, min_prec):
|
|
201 while self.PeakPrec >= min_prec:
|
|
202 op_prec = self.PeakPrec
|
|
203 op = self.Consume(self.Peak)
|
|
204 rhs = self.parsePrimary()
|
|
205 while self.PeakPrec > op_prec:
|
|
206 rhs = self.parseBinopRhs(rhs, self.PeakPrec)
|
149
|
207 lhs = self.sema.actOnBinop(lhs, op.typ, rhs, op.loc)
|
148
|
208 return lhs
|
|
209
|