-
Notifications
You must be signed in to change notification settings - Fork 0
/
chlang
executable file
·455 lines (425 loc) · 16.7 KB
/
chlang
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
#!/usr/bin/python3
"""
Description: Churro frontend + driver
Author: Caian Benedicto
"""
Name='chlang'
Version = '1.0.3'
import sys, re, argparse, subprocess, tempfile
import Runtime.debug, Runtime.release
def dprint(x):
pass
#print(x)
def eprint(x):
sys.stderr.write(x+'\n')
class srcfile:
def __init__(self, filename):
try:
self.f = open(filename, 'rt')
self.line = 1
except OSError:
eprint("No such file '"+filename+"'!")
exit(1)
def read_one(self):
c = self.f.read(1)
if c == '\n':
self.line = self.line + 1
return c
def get_line(self):
return self.line
def close(self):
self.f.close()
def getChurro(stream):
while True:
c = stream.read_one()
if c == '{':
break
elif c == '':
return True
dprint('Found a churro!')
c = stream.read_one()
if c == 'o':
dprint('It is a left unfilled churro!')
if stream.read_one() != '}':
eprint('Malformed churro!!')
return False
n = 0
while True:
c = stream.read_one()
if c == '=':
n = n+1
elif c == '}':
break
else:
eprint('Malformed churro!!')
return False
dprint('Its size is ' + str(n) + '!')
return ('lu', n)
elif c == '*':
dprint('It is a left filled churro!')
if stream.read_one() != '}':
eprint('Malformed churro!!')
return False
n = 0
while True:
c = stream.read_one()
if c == '=':
n = n+1
elif c == '}':
break
else:
eprint('Malformed churro!!')
return False
dprint('Its size is ' + str(n) + '!')
return ('lf', n)
elif c == '=':
dprint('It is a right churro!')
n = 1
while True:
c = stream.read_one()
if c != '=':
break
n = n+1
dprint('Its size is ' + str(n))
if c != '{':
eprint('Malformed churro!!')
return False
c = stream.read_one()
if c == 'o':
dprint('It is unfilled!')
f = 'ru'
elif c == '*':
dprint('It is filled!')
f = 'rf'
else:
eprint('Malformed churro!!')
return False
if stream.read_one() != '}':
eprint('Malformed churro!!')
return False
return (f, n)
elif c == '{':
c = stream.read_one()
if stream.read_one() != '}':
eprint('Malformed churro!!')
return False
if c == 'o':
dprint('It is a tiny right unfilled churro!')
return ('ru', 0)
elif c == '*':
dprint('It is a tiny right filled churro!')
return ('rf', 0)
else:
eprint('Malformed churro!!')
return False
llvm_counter = 0
def getreg():
global llvm_counter
llvm_counter += 1
return '%r' + str(llvm_counter)
loop_stack = []
label_counter = 1
def getlabel():
global label_counter
label_counter += 1
return 'label' + str(label_counter)
def mkinst(c):
global loop_stack
############################################################
if c[0] == 'lu':
return 'call void @__push(i32 ' + str(c[1]) + ')'
############################################################
elif c[0] == 'lf':
return 'call void @__push(i32 -' + str(c[1]) + ')'
############################################################
elif c[0] == 'ru':
if c[1] == 0: # pop A; discard A
return 'call i32 @__pop()'
elif c[1] == 1: # pop A, B; push (B + A)
r1 = getreg()
r2 = getreg()
r3 = getreg()
return r1 + ' = call i32 @__pop()\n' + r2 + ' = call i32 @__pop()\n' + r3 + ' = add i32 ' + r1 + ', ' + r2 + '\ncall void @__push(i32 ' + r3 + ')'
elif c[1] == 2: # pop A, B; push (B - A)
r1 = getreg()
r2 = getreg()
r3 = getreg()
return r1 + ' = call i32 @__pop()\n' + r2 + ' = call i32 @__pop()\n' + r3 + ' = sub i32 ' + r1 + ', ' + r2 + '\ncall void @__push(i32 ' + r3 + ')'
elif c[1] == 3: # pop A; if A = 0, jump to churro after next occurence of {===={o}
t = getlabel()
q = getlabel()
loop_stack.append((t, q))
r1 = getreg()
r2 = getreg()
return r1 + ' = call i32 @__pop()\n' + r2 + ' = icmp eq i32 ' + r1 + ', 0\nbr i1 ' + r2 + ', label %' + q + ', label %' + t + '\r' + t + ':'
elif c[1] == 4: # pop A; if A != 0, jump to churro after last occurence of {==={o}
if len(loop_stack) == 0:
eprint('Unmatched {===={o} churro!!')
return False
l = loop_stack.pop()
t = l[0]
q = l[1]
r1 = getreg()
r2 = getreg()
i = r1 + ' = call i32 @__pop()\n' + r2 + ' = icmp ne i32 ' + r1 + ', 0\nbr i1 ' + r2 + ', label %' + t + ', label %' + q + '\r' + q + ':'
return i
elif c[1] == 5: # pop A, B; store B in memory location A
r1 = getreg()
r2 = getreg()
return r1 + ' = call i32 @__pop()\n' + r2 + ' = call i32 @__pop()\ncall void @__writem(i32 ' + r1 + ', i32 ' + r2 + ')'
elif c[1] == 6: # pop A; push the value in memory location A to stack
r1 = getreg()
r2 = getreg()
return r1 + ' = call i32 @__pop()\n' + r2 + ' = call i32 @__readm(i32 ' + r1 + ')\ncall void @__push(i32 ' + r2 + ')'
elif c[1] == 7: # pop A; print A as an integer
r1 = getreg()
return r1 + ' = call i32 @__pop()\ncall void @__printi(i32 ' + r1 + ')'
elif c[1] == 8: # pop A; print A as an ASCII character
r1 = getreg()
return r1 + ' = call i32 @__pop()\ncall void @__printc(i32 ' + r1 + ')'
elif c[1] == 9: # read a single character from stdin and push it to the stack
r1 = getreg()
return r1 + ' = call i32 @__readc()\ncall void @__push(i32 ' + r1 + ')'
elif c[1] == 10: # exit the program
return 'ret i32 0\r; dead code'
############################################################
elif c[0] == 'rf':
if c[1] == 0: # peek A; discard A
return 'call i32 @__peek()'
elif c[1] == 1: # peek A, B; push (B + A)
r1 = getreg()
r2 = getreg()
r3 = getreg()
return r1 + ' = call i32 @__peek()\n' + r2 + ' = call i32 @__peekl()\n' + r3 + ' = add i32 ' + r1 + ', ' + r2 + '\ncall void @__push(i32 ' + r3 + ')'
elif c[1] == 2: # peek A, B; push (B - A)
r1 = getreg()
r2 = getreg()
r3 = getreg()
return r1 + ' = call i32 @__peek()\n' + r2 + ' = call i32 @__peekl()\n' + r3 + ' = sub i32 ' + r1 + ', ' + r2 + '\ncall void @__push(i32 ' + r3 + ')'
elif c[1] == 3: # peek A; if A = 0, jump to churro after next occurence of {===={o}
t = getlabel()
q = getlabel()
loop_stack.append((t, q))
r1 = getreg()
r2 = getreg()
return r1 + ' = call i32 @__peek()\n' + r2 + ' = icmp eq i32 ' + r1 + ', 0\nbr i1 ' + r2 + ', label %' + q + ', label %' + t + '\r' + t + ':'
elif c[1] == 4: # peek A; if A != 0, jump to churro after last occurence of {==={o}
if len(loop_stack) == 0:
eprint('Unmatched {===={*} churro!!')
return False
l = loop_stack.pop()
t = l[0]
q = l[1]
r1 = getreg()
r2 = getreg()
i = r1 + ' = call i32 @__peek()\n' + r2 + ' = icmp ne i32 ' + r1 + ', 0\nbr i1 ' + r2 + ', label %' + t + ', label %' + q + '\r' + q + ':'
llvm_qlast = ''
return i
elif c[1] == 5: # peek A, B; store B in memory location A
r1 = getreg()
r2 = getreg()
return r1 + ' = call i32 @__peek()\n' + r2 + ' = call i32 @__peekl()\ncall void @__writem(i32 ' + r1 + ', i32 ' + r2 + ')'
elif c[1] == 6: # peek A; push the value in memory location A to stack
r1 = getreg()
r2 = getreg()
return r1 + ' = call i32 @__peek()\n' + r2 + ' = call i32 @__readm(i32 ' + r1 + ')\ncall void @__push(i32 ' + r2 + ')'
elif c[1] == 7: # peek A; print A as an integer
r1 = getreg()
return r1 + ' = call i32 @__peek()\ncall void @__printi(i32 ' + r1 + ')'
elif c[1] == 8: # peek A; print A as an ASCII character
r1 = getreg()
return r1 + ' = call i32 @__peek()\ncall void @__printc(i32 ' + r1 + ')'
elif c[1] == 9: # read a single character from stdin and push it to the stack
r1 = getreg()
return r1 + ' = call i32 @__readc()\ncall void @__push(i32 ' + r1 + ')'
elif c[1] == 10: # exit the program
return 'ret 0'
#invalid instruction
eprint("Invalid churro '"+c+"'!!")
return ''
def main():
# Argument parsing
#TODO: Add support for piping
#TODO: Add support for .o
#TODO: Get rid of this stupid argument parsing library!
parser = argparse.ArgumentParser(description='The Churro language frontend for LLVM.')
parser.add_argument('-o', metavar='<file>', dest='output', type=str,
default='',
help='Output file')
parser.add_argument('-S', dest='assembler', action='store_true',
default=False,
help='Only run preprocess and compilation steps')
parser.add_argument('-emit-llvm', dest='llvm', action='store_true',
default=False,
help='Use the LLVM representation for assembler and object files')
parser.add_argument('-save-temps', dest='temps', action='store_true',
default=False,
help='Save intermediate compilation results')
parser.add_argument('-v','--version', dest='ver', action='store_true',
default=False,
help='Show compiler version')
parser.add_argument('-clang-bin', metavar='<file>', dest='clangb', type=str,
default='clang++',
help='Clang++ binary override')
parser.add_argument('-not-picky', dest='notpicky', action='store_true',
default=False,
help='Do not check for clang version')
#TODO: Implement -c
#parser.add_argument('-c', action='store_true', default=False,
# help='')
parser.add_argument('-g', dest='debug', action='store_true', default=False,
help='Generate runtime debug verbose')
parser.add_argument('-O', dest='opt', type=int, default=None,
help='Optimization level 0-4')
parser.add_argument('-x', metavar='<language>', dest='intype', type=str,
default='',
help='Treat subsequent input files as having type <language>')
parser.add_argument('sources', metavar='<input>', type=str, nargs='?',
help='Source file')
lopts = parser.parse_args()
# Version
if lopts.ver:
print(Name+' version '+Version)
exit(0)
# Source listing
if lopts.sources == None:
eprint('No input files!');
exit(1)
fin = lopts.sources
fmodule = re.sub(r'.*/', '', fin)
# Source type processing
fname = ''
stage = -1
if lopts.intype == '': # Guess from file type
if re.match(r'.*\.ch$', fin) != None:
fname = re.sub(r'\.ch$', '', fmodule)
stage = 0 # 0 - .ch -> .ll
elif re.match(r'.*\.ll$', fin) != None:
fname = re.sub(r'\.ll$', '', fmodule)
stage = 1 # 1 - .ll -> .s
elif re.match(r'.*\.s$', fin) != None:
fname = re.sub(r'\.s$', '', fmodule)
stage = 2 # 2 = .s -> binary
else:
eprint(" file '"+fmodule+"' not recognized!!")
elif lopts.intype == 'churro':
fname = re.sub(r'\.ch$', '', fmodule)
stage = 0 # 0 - .ch -> .ll
elif lopts.intype == 'ir':
fname = re.sub(r'\.ll$', '', fmodule)
stage = 1 # 1 - .ll -> .s
elif lopts.intype == 'assembly':
fname = re.sub(r'\.s$', '', fmodule)
stage = 2 # 2 = .s -> binary
else:
eprint("Unsupported input format '" + lopts.intype + "'!")
exit(1)
# Output selection
fout = ''
if lopts.assembler:
if lopts.llvm:
fout = fname + '.ll'
else:
fout = fname + '.s'
else:
fout = fname
if lopts.output != '':
fout = lopts.output
# Temporary output (always created for simplicity)
with tempfile.TemporaryDirectory() as tempdir:
# Runtime selection
if lopts.debug:
llvm_pre1 = Runtime.debug.llvm_pre1
llvm_pre2 = Runtime.debug.llvm_pre2
llvm_post = Runtime.debug.llvm_post
else:
llvm_pre1 = Runtime.release.llvm_pre1
llvm_pre2 = Runtime.release.llvm_pre2
llvm_post = Runtime.release.llvm_post
# Stage 0 - Parsing + LLVM code generation
if stage == 0:
code_llvm = '; This code was generated using ' + Name + ' ' + str(Version) + '\n\n'
code_llvm += llvm_pre1 + fmodule + llvm_pre2
fsrc = srcfile(sys.argv[1])
while True:
c = getChurro(fsrc)
if c == True:
break
elif c == False:
eprint('Compilation Error at line ' + str(fsrc.get_line()) + '!')
exit()
else:
i = mkinst(c)
if i == False:
eprint('Compilation Error at line ' + str(fsrc.get_line()) + '!')
exit(1)
i = ' ' + i.replace('\n', '\n ').replace('\r', '\n')
code_llvm += i + '\n'
code_llvm += llvm_post
fin = tempdir + '/' + fname + '.ll'
lopts.intype = 'ir'
with open(fin, 'wt') as f:
f.write(code_llvm)
fsrc.close()
if lopts.temps:
with open(fname + '.ll', 'wt') as f:
f.write(code_llvm)
if lopts.assembler:
if lopts.llvm:
if lopts.opt != None:
eprint('Option not used: -O'+str(lopts.opt))
with open(fout, 'wt') as f:
f.write(code_llvm)
exit(0)
else:
if lopts.llvm:
eprint('Option not used: -emit-llvm')
else:
if lopts.llvm:
eprint('Option not used: -emit-llvm')
if lopts.debug:
eprint('Option not used: -g')
# Check for clang...
try:
args = [lopts.clangb, '--version']
out = subprocess.check_output(args, stderr=subprocess.STDOUT)
if not lopts.notpicky:
out = str(out, encoding='utf-8')
out = re.search(r'clang version [0-9]+\.[0-9]+', out)
out = out.group(0) if out != None else ''
out = re.search(r'[0-9]+\.[0-9]+', out)
out = out.group(0).split('.') if out != None else ['x','x']
try:
out = [int(x) for x in out]
if len(out) != 2:
eprint('Cannot determine the version of clang, make it sure that the version is compatible with the code generated')
if out[0] < 3 or (out[0] == 3 and out[1] < 5):
eprint('This compiler was designed for clang 3.5.0, it appears that you are using an old version of LLVM, this may cause problems')
except (ValueError, TypeError):
eprint('Cannot determine the version of clang, make it sure that the version is compatible with the code generated')
except (subprocess.CalledProcessError, EnvironmentError):
eprint('Failed to invoke clang, make sure it is installed correctly!')
exit(1)
# Setup clang
pipe = None
args = [lopts.clangb]
if lopts.opt:
args.append('-O'+str(lopts.opt))
if lopts.temps:
args.append('-save-temps')
if lopts.assembler:
args.append('-S')
if lopts.output:
args.append('-o')
args.append(lopts.output)
if lopts.intype != '':
args.append('-x'+lopts.intype)
args.append(fin)
# Call clang
try:
exit(subprocess.call(args))
except EnvironmentError:
eprint('Something wrong happened while invoking clang!')
exit(1)
if __name__=="__main__":
main()