-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.rb
426 lines (375 loc) · 8.89 KB
/
parser.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
require_relative "ast.rb"
require_relative "sym.rb"
require_relative "types.rb"
require_relative "label.rb"
$opOprec = {
:SLASH => 7,
:STAR => 7,
:PLUS => 6,
:MINUS => 6,
:GT => 4,
:GE => 4,
:LT => 4,
:LE => 4,
:EQ_EQ => 3,
:NE => 3
}
class Parser
def initialize(tokens, sym)
@tokens = tokens
@current = 0
@token = nil
@sym = sym
@functionId = 0
end
def parse
advance
statements
end
def statements
list = []
while 1
#list.push funcDecl
type = parseType(@token.type)
check(:IDENT)
if peek.type == :LPAREN
list.push funcDecl(type)
else
list.push varDecl(type)
end
if @token.type == :EOF
break
end
end
Statements.new(list)
end
def singleStmt
case @token.type
when :PRINT
printStmt
when :INT, :CHAR, :VOID, :LONG
type = parseType(@token.type)
varDecl(type)
when :IDENT
assignmentStmt
when :IF
ifStmt
when :WHILE
whileStmt
when :FOR
forStmt
when :RETURN
returnStmt
else
error(@token.line, "Syntax error", @token.type)
end
end
def compoundStatement
# single = true allows only one statement
list = []
match(:LBRACE, "{")
while 1
stmt = singleStmt
if [PrintStmt, AssignmentStmt, FuncCall, ReturnStmt].include? stmt.class
match(:SEMI, ";")
end
list.push stmt
if @token.type == :RBRACE
match(:RBRACE, "}")
break
end
end
Statements.new list
end
def funcDecl(type)
#type = parseType(@token.type)
line = @token.line
#advance
#check(:IDENT)
name = @token.literal
endlabel = Label::label
nameslot = @sym.addglob(@token.literal,type, :S_FUNCTION, endlabel)
@functionId = nameslot
advance
match(:LPAREN, "(")
match(:RPAREN, ")")
body = compoundStatement
if not type == :P_VOID
if not body.stmts[-1].class == ReturnStmt
error(line, "No return from a function with non-void type")
end
end
FuncDecl.new(name, nameslot, body)
end
def parseType(type)
tt = {:VOID => :P_VOID, :CHAR => :P_CHAR, :INT => :P_INT, :LONG => :P_LONG}
t = if tt[type] != nil then tt[type] else error(@token.line, "Illegal type, token #{type}") end
advance
if @token.type == :STAR
t = Types::pointerTo(t)
advance
end
t
end
def varDecl(type)
#type = parseType(@token.type)
#advance
#check(:IDENT)
vars = []
while 1
id = @sym.addglob(@token.literal, type, :S_VARIABLE)
ident = @token.literal
advance
vars.push VarDecl.new(ident, id)
if @token.type == :SEMI
match(:SEMI, ";")
break
end
if @token.type == :COMMA
match(:COMMA, ",")
check(:IDENT)
next
end
error(@token.line, "missing , or ; after identifier")
end
Statements.new(vars)
end
def returnStmt
rType = @sym.names[@functionId]["type"]
if rType == :P_VOID
error(@token.line, "Can't return from a void function")
end
match(:RETURN, "return")
match(:LPAREN, "(")
expr = binexp(0)
comp = Types::compatibleTypes(expr.type, rType, true)
case comp
when :INCOMPATIBLE
error(@token.line, "Incompatible types")
when :WIDEN_LEFT
expr.type = rType
end
match(:RPAREN, ")")
ReturnStmt.new(expr, @functionId)
end
def assignmentStmt
#left = the expression to be stored
#right = the LVALUE where the expression is to be stored
check(:IDENT)
if peek.type == :LPAREN
return funccall
end
if((id = @sym.findglob(@token.literal)) == -1)
error(@token.line, "Undeclared variable", @token.literal)
end
advance
right = LVIdent.new(@token.literal, id, @sym.names[id]["type"])
match(:EQUALS, "=")
left = binexp(0)
comp = Types::compatibleTypes(left.type, right.type, true)
case comp
when :INCOMPATIBLE
error(@token.line, "Incompatilbe types in assignment")
when :WIDEN_LEFT
left.type = right.type
end
t = AssignmentStmt.new(left, right)
#match(:SEMI, ";")
t
end
def ifStmt
match(:IF, "if")
match(:LPAREN, "(")
cond = binexp(0)
if not [:EQ_EQ, :NE, :LT, :LE, :GT, :GE].include? cond.a_type
fatal("bad comparision operator.")
end
match(:RPAREN, ")")
thenBranch = compoundStatement
elseBranch = nil
if(@token.type == :ELSE)
advance
elseBranch = compoundStatement
end
IfStmt.new(cond, thenBranch, elseBranch)
end
def whileStmt
match(:WHILE, "while")
match(:LPAREN, "(")
cond = binexp(0)
if not [:EQ_EQ, :NE, :LT, :LE, :GT, :GE].include? cond.a_type
fatal("bad comparision operator.")
end
match(:RPAREN, ")")
body = compoundStatement
WhileStmt.new(cond,body)
end
def forStmt
match(:FOR, "for")
match(:LPAREN, "(")
preop = singleStmt
#puts preop, @token
match(:SEMI, ";")
cond = binexp(0)
if not [:EQ_EQ, :NE, :LT, :LE, :GT, :GE].include? cond.a_type
fatal("bad comparision operator.")
end
match(:SEMI, ")")
postop = singleStmt
match(:RPAREN, ")")
body = compoundStatement
body.stmts.push postop
while_ = WhileStmt.new(cond, body)
Statements.new([preop, while_])
end
def printStmt
match(:PRINT, "print")
tree = binexp(0)
comp = Types::compatibleTypes(:P_INT, tree.type)
if comp == :WIDEN_RIGHT
tree.type = :INT
end
#match(:SEMI, ";")
PrintStmt.new(tree)
end
def funccall
if ((id = @sym.findglob(previous.literal)) == -1)
error(previous.line,"Undeclared function '#{previous.literal}'")
end
if not @sym.names[id]["s_type"] == :S_FUNCTION
error(previous.line, "Calling a non-function.")
end
advance
match(:LPAREN, "(")
args = []
args.push binexp(0)
match(:RPAREN, ")")
FuncCall.new(@sym.names[id]["type"], args, id)
end
def prefix
case @token.type
when :AMPER
advance
expr = prefix
if expr.class != Ident
error(@token.line, "& must be followed by an identifier")
end
Addr.new(Types::pointerTo(expr.type), expr)
when :STAR
advance
expr = prefix
if expr.class != Ident and expr.class != Deref
error(@token.line, "* must be followed by an identifier or *")
end
Deref.new(Types::valueAt(expr.type), expr)
else
primary
end
end
def primary
n = nil
case @token.type
when :NUMBER
val = @token.literal.to_i
if val >= 0 and val < 256
n = IntLit.new(val, :P_CHAR)
else
n = IntLit.new(val, :P_INT)
end
when :IDENT
if peek.type == :LPAREN
return funccall
end
id = @sym.findglob(@token.literal)
if(id == -1)
error(@token.line, "Unknown variable '#{@token.literal}'", @token.type)
end
n = Ident.new(@token.literal, id, @sym.names[id]["type"])
else
error(@token.line, "syntax error", @token.type)
end
advance
n
end
def binexp(prec)
left = prefix
token_= @token
if token_.type == :SEMI || token_.type == :RPAREN
return left
end
while(op_prec(token_) > prec)
advance
right = binexp($opOprec[token_.type])
comp = Types::compatibleTypes(left.type, right.type)
case comp
when :INCOMPATIBLE
error(@token.line, "incompatible types.")
when :WIDEN_LEFT
left.type = :P_INT
when :WIDEN_RIGHT
right.type = :P_INT
end
scaling = Types::scaling(left, right, token_)
if scaling != nil
case scaling[0]
when :SCALE_LEFT
left = Scale.new(left, right.type, scaling[1])
when :SCALE_RIGHT
right = Scale.new(right, left.type, scaling[1])
end
end
left = Binary.new(token_.type, left.type, left, right)
token_= @token
if (token_.type == :SEMI || token_.type == :RPAREN)
return left
end
end
return left
end
def advance
#if(!isAtEnd)
@current += 1
#end
@token = previous
end
def isAtEnd
peek.type == :EOF
end
def peek
@tokens[@current]
end
def previous
@tokens[@current-1]
end
def check(type)
if(@token.type == type)
return true
else
fatal("unexpected #{@token.type}")
end
end
def match(type, what)
if(@token.type == type)
advance
return previous
else
error(previous.line, "excpected #{what}", nil)
end
end
def op_prec(token)
#puts "prec of #{token.type}"
prec = $opOprec[token.type]
if(prec == 0 || prec == nil)
error(token.line, "psyntax error", token.type)
end
prec
end
def error(line, message, type=nil)
puts "Line #{line}: #{message}" + if type then ",token #{type}" else "" end
exit(1)
end
def fatal(message)
puts message
exit(1)
end
end