-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlisp2cpp_test.py
403 lines (324 loc) · 10.5 KB
/
lisp2cpp_test.py
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
import unittest
from pathlib import Path
from subprocess import PIPE, Popen
from tempfile import TemporaryDirectory
from lisp2cpp import (
LAMBDA,
LPAREN,
QUOTE,
RPAREN,
LambdaExp,
Lisp2Cpp,
OpExp,
Parser,
SExp,
TokenType,
VarExp,
lisp_lexer,
)
class TokenizerTest(unittest.TestCase):
@staticmethod
def tokenize(text):
return list(lisp_lexer.tokens(text))
@staticmethod
def token_types(tokens):
return [_.type for _ in tokens]
@staticmethod
def token_values(tokens):
return [_.value for _ in tokens]
def test_1(self):
var0 = "var0"
var1 = "var1"
var2 = "123abc"
expr = f"( * {var0} {var1} {var2}))"
tokens = self.tokenize(expr)
self.assertEqual(
self.token_types(tokens),
[
TokenType.LParen,
TokenType.Identifier,
TokenType.Identifier,
TokenType.Identifier,
TokenType.Identifier,
TokenType.RParen,
TokenType.RParen,
],
)
self.assertEqual(
self.token_values(tokens), [LPAREN, "*", var0, var1, var2, RPAREN, RPAREN]
)
def test_2(self):
expr = "( lambda (x) (+ x 1))"
tokens = self.tokenize(expr)
self.assertEqual(
self.token_types(tokens),
[
TokenType.LParen,
TokenType.Identifier,
TokenType.LParen,
TokenType.Identifier,
TokenType.RParen,
TokenType.LParen,
TokenType.Identifier,
TokenType.Identifier,
TokenType.Identifier,
TokenType.RParen,
TokenType.RParen,
],
)
self.assertEqual(
self.token_values(tokens),
[
LPAREN,
LAMBDA,
LPAREN,
"x",
RPAREN,
LPAREN,
"+",
"x",
"1",
RPAREN,
RPAREN,
],
)
def test_comments_1(self):
expr = ")(x;y()\n"
tokens = self.tokenize(expr)
self.assertEqual(
self.token_types(tokens),
[
TokenType.RParen,
TokenType.LParen,
TokenType.Identifier,
TokenType.Comment,
],
)
def test_comments_2(self):
expr = ")(x;y()\n );omg"
tokens = self.tokenize(expr)
self.assertEqual(
self.token_types(tokens),
[
TokenType.RParen,
TokenType.LParen,
TokenType.Identifier,
TokenType.Comment,
TokenType.RParen,
TokenType.Comment,
],
)
def test_no_whitespace(self):
expr = "(lambda(x)(+ x 1))"
tokens = self.tokenize(expr)
self.assertEqual(
self.token_types(tokens),
[
TokenType.LParen,
TokenType.Identifier,
TokenType.LParen,
TokenType.Identifier,
TokenType.RParen,
TokenType.LParen,
TokenType.Identifier,
TokenType.Identifier,
TokenType.Identifier,
TokenType.RParen,
TokenType.RParen,
],
)
self.assertEqual(
self.token_values(tokens),
[
LPAREN,
LAMBDA,
LPAREN,
"x",
RPAREN,
LPAREN,
"+",
"x",
"1",
RPAREN,
RPAREN,
],
)
def test_emptylist_1(self):
expr = "'()"
tokens = self.tokenize(expr)
self.assertEqual(
self.token_types(tokens),
[TokenType.Quote, TokenType.LParen, TokenType.RParen],
)
self.assertEqual(self.token_values(tokens), [QUOTE, LPAREN, RPAREN])
def test_emptylist_2(self):
expr = "'( )"
tokens = self.tokenize(expr)
self.assertEqual(
self.token_types(tokens),
[TokenType.Quote, TokenType.LParen, TokenType.RParen],
)
self.assertEqual(self.token_values(tokens), [QUOTE, LPAREN, RPAREN])
def test_emptylist_3(self):
varname = "var"
expr = f"'({varname})"
tokens = self.tokenize(expr)
self.assertEqual(
self.token_types(tokens),
[TokenType.Quote, TokenType.LParen, TokenType.Identifier, TokenType.RParen],
)
self.assertEqual(self.token_values(tokens), [QUOTE, LPAREN, varname, RPAREN])
def test_booleans(self):
expr = "((#t)(#f)(42))"
tokens = self.tokenize(expr)
self.assertEqual(
self.token_values(tokens),
[
LPAREN,
LPAREN,
"#t",
RPAREN,
LPAREN,
"#f",
RPAREN,
LPAREN,
"42",
RPAREN,
RPAREN,
],
)
class ParserTest(unittest.TestCase):
@staticmethod
def parse(text):
return Parser.parse(text)
def test_1(self):
varname = "var"
expr = f"(* {varname} 1)"
parse = self.parse(expr)
self.assertIsInstance(parse, SExp)
self.assertEqual(parse.operator.value, Parser.ops["*"])
self.assertEqual(parse.operands, [VarExp(varname), 1])
def test_lambda(self):
varname = "x"
expr = f"(lambda ({varname}) (+ {varname} 1))"
parse = self.parse(expr)
expectedBody = SExp(operator=OpExp("Add"), operands=[VarExp(varname), 1])
self.assertIsInstance(parse, LambdaExp)
self.assertEqual(parse.arglist, [VarExp(varname)])
self.assertEqual(parse.body, expectedBody)
class Lisp2CppTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp_dir = TemporaryDirectory()
cls.temp_dir_name = Path(cls.temp_dir.name)
@classmethod
def tearDownClass(cls):
cls.temp_dir.cleanup()
@staticmethod
def codegen(text):
return Lisp2Cpp(text).codegen()
@property
def compiler_outfile(self):
return self.temp_dir_name / "a.out"
def check_cppeval(self, lisp_code, expected_result):
cpp_code = "#include <type_traits>\n\r\n\r"
cpp_code += Lisp2Cpp(lisp_code).codegen(evaluate=False, include_header=True)
cpp_code += "\n\r\n\r"
cpp_code += f"static_assert(std::is_same<Result, {expected_result}>::value);"
self.check_compiles(cpp_code)
def check_compiles(self, code):
with Popen(["echo", code], stdout=PIPE) as codegen_process, Popen(
["c++", "-xc++", "-std=c++1z", "-", "-c", "-o", self.compiler_outfile],
stdin=codegen_process.stdout,
stdout=PIPE,
stderr=PIPE,
) as compile_process:
out, err = compile_process.communicate()
self.assertEqual(compile_process.returncode, 0, (out, err))
def test_varmap_1(self):
exp = "(lambda (x y) (+ x y z))"
lisp2cpp = Lisp2Cpp(exp)
self.assertEqual(set(lisp2cpp.varmap), {"x", "y", "z"})
def test_compile_subprocess(self):
self.check_compiles("int main(){}")
with self.assertRaises(AssertionError):
self.check_compiles("int main(){")
def test_codegen_1(self):
self.check_cppeval("(+ 2 3)", "Int<5>")
def test_codegen_2(self):
exp = "((lambda (x y) (+ x 1 y)) 2 3)"
self.check_cppeval(exp, "Int<6>")
def test_codegen_3(self):
exp = "(or #t #f #t)"
self.check_cppeval(exp, "True")
def test_codegen_4(self):
exp = "(if #t 1 3)"
self.check_cppeval(exp, "Int<1>")
def test_codegen_5(self):
list_exp = "(cons 0 (cons 1 (cons 2 3)))"
exp = f"(car (cdr (cdr {list_exp})))"
self.check_cppeval(exp, "Int<2>")
def test_let(self):
exp = "(let ((x 1)(y 2)) (+ x y))"
self.check_cppeval(exp, "Int<3>")
def test_factorial(self):
def fact(n):
if n == 0:
return 1
return n * fact(n - 1)
for integer in [0, 1, 10]:
exp = (
"(letrec ((fact (lambda (n)"
" (if (= 0 n)"
" 1"
" (* n (fact (- n 1)))))))"
f" (fact {integer}))"
)
self.check_cppeval(exp, f"Int<{fact(integer)}>")
def test_mapcar(self):
def mapcar_exp(func_exp, list_exp):
return (
"(letrec ((mapcar (lambda (func list)"
" (if (null? list)"
" '()"
" (cons (func (car list)) (mapcar func (cdr list)))"
" ))))"
f" (mapcar {func_exp} {list_exp}))"
)
list_exp = "'(1 2 3)"
double_fun = "(lambda (arg) (* arg 2))"
self.check_cppeval(
mapcar_exp(func_exp=double_fun, list_exp=list_exp),
"Cons<Int<2>, Cons<Int<4>, Cons<Int<6>, EmptyList>>>",
)
def test_mess_with_keywords(self):
exp = """(let ((if 1)
(lambda_var 1)
(++ 1)
(and_exp 1)
(123abc 1) )
(+ if lambda_var and_exp ++ 123abc))"""
self.check_cppeval(exp, "Int<5>")
def test_fib(self):
def fib_exp(n):
return (
"(letrec ((fib (lambda (n)"
" (if (<= n 0)"
" 1"
" (+ (fib (- n 1)) (fib (- n 2)))))))"
f" (fib {n}))"
)
def fib_py(n):
if n <= 0:
return 1
return fib_py(n - 1) + fib_py(n - 2)
for n in range(10):
self.check_cppeval(fib_exp(n), f"Int<{fib_py(n)}>")
def test_unary_minus(self):
self.check_cppeval("(- 1)", "Int<-1>")
self.check_cppeval("(- 0)", "Int<0>")
def test_lots_of_minuses(self):
self.check_cppeval("(- 1 2)", "Int<-1>")
self.check_cppeval("(- 1 2 3)", "Int<-4>")
if __name__ == "__main__":
unittest.main()