Debian Codegraph @

tests/test_c_generator.py

raw
1 import os
2 import sys
3 import unittest
4
5 # Run from the root dir
6 sys.path.insert(0, ".")
7
8 from pycparser import c_parser, c_generator, c_ast, parse_file
9 from tests.test_util import cpp_supported, cpp_path, cpp_args
10
11 _c_parser = c_parser.CParser()
12
13
14 def compare_asts(ast1, ast2):
15 """Compares two ASTs recursively just enough for the purpose of testing.
16
17 Since this function is recursive it also accepts non-ast parameters, in
18 which case it compares them literally (with ==) or recursively (for tuples
19 or lists).
20 """
21 # After the initial `if`, all the `elif` clauses assume that the types of
22 # ast1 and ast2 are the same.
23 if type(ast1) is not type(ast2):
24 return False
25 elif isinstance(ast1, (list, tuple)):
26 if len(ast1) != len(ast2):
27 return False
28 for i in range(len(ast1)):
29 if not compare_asts(ast1[i], ast2[i]):
30 return False
31 return True
32 elif isinstance(ast1, c_ast.Node):
33 for attr in ast1.attr_names:
34 attr1 = getattr(ast1, attr)
35 attr2 = getattr(ast2, attr)
36 if not compare_asts(attr1, attr2):
37 return False
38 children1 = ast1.children()
39 children2 = ast2.children()
40 if len(children1) != len(children2):
41 return False
42 for i in range(len(children1)):
43 if not compare_asts(children1[i], children2[i]):
44 return False
45 return True
46 else:
47 return ast1 == ast2
48
49
50 def parse_to_ast(src):
51 return _c_parser.parse(src)
52
53
54 class TestFunctionDeclGeneration(unittest.TestCase):
55 class _FuncDeclVisitor(c_ast.NodeVisitor):
56 def __init__(self):
57 self.stubs = []
58
59 def visit_FuncDecl(self, node):
60 gen = c_generator.CGenerator()
61 self.stubs.append(gen.visit(node))
62
63 def test_partial_funcdecl_generation(self):
64 src = r"""
65 void noop(void);
66 void *something(void *thing);
67 int add(int x, int y);"""
68 ast = parse_to_ast(src)
69 v = TestFunctionDeclGeneration._FuncDeclVisitor()
70 v.visit(ast)
71 self.assertEqual(len(v.stubs), 3)
72 self.assertTrue(r"void noop(void)" in v.stubs)
73 self.assertTrue(r"void *something(void *thing)" in v.stubs)
74 self.assertTrue(r"int add(int x, int y)" in v.stubs)
75
76
77 class TestCtoC(unittest.TestCase):
78 def _run_c_to_c(self, src, *args, **kwargs):
79 ast = parse_to_ast(src)
80 generator = c_generator.CGenerator(*args, **kwargs)
81 return generator.visit(ast)
82
83 def _assert_ctoc_correct(self, src, *args, **kwargs):
84 """Checks that the c2c translation was correct by parsing the code
85 generated by c2c for src and comparing the AST with the original
86 AST.
87
88 Additional arguments are passed to CGenerator.__init__.
89 """
90 src2 = self._run_c_to_c(src, *args, **kwargs)
91 self.assertTrue(
92 compare_asts(parse_to_ast(src), parse_to_ast(src2)),
93 "{!r} != {!r}".format(src, src2),
94 )
95 return src2
96
97 def test_trivial_decls(self):
98 self._assert_ctoc_correct("int a;")
99 self._assert_ctoc_correct("int b, a;")
100 self._assert_ctoc_correct("int c, b, a;")
101 self._assert_ctoc_correct("auto int a;")
102 self._assert_ctoc_correct("register int a;")
103 self._assert_ctoc_correct("_Thread_local int a;")
104
105 def test_complex_decls(self):
106 self._assert_ctoc_correct("int** (*a)(void);")
107 self._assert_ctoc_correct("int** (*a)(void*, int);")
108 self._assert_ctoc_correct("int (*b)(char * restrict k, float);")
109 self._assert_ctoc_correct("int (*b)(char * _Atomic k, float);")
110 self._assert_ctoc_correct("int (*b)(char * _Atomic volatile k, float);")
111 self._assert_ctoc_correct("int test(const char* const* arg);")
112 self._assert_ctoc_correct("int test(const char** const arg);")
113
114 def test_alignment(self):
115 self._assert_ctoc_correct("_Alignas(32) int b;")
116 self._assert_ctoc_correct("int _Alignas(32) a;")
117 self._assert_ctoc_correct("_Alignas(32) _Atomic(int) b;")
118 self._assert_ctoc_correct("_Atomic(int) _Alignas(32) b;")
119 self._assert_ctoc_correct("_Alignas(long long) int a;")
120 self._assert_ctoc_correct("int _Alignas(long long) a;")
121 self._assert_ctoc_correct(r"""
122 typedef struct node_t {
123 _Alignas(64) void* next;
124 int data;
125 } node;
126 """)
127 self._assert_ctoc_correct(r"""
128 typedef struct node_t {
129 void _Alignas(64) * next;
130 int data;
131 } node;
132 """)
133
134 def test_ternary(self):
135 self._assert_ctoc_correct("""
136 int main(void)
137 {
138 int a, b;
139 (a == 0) ? (b = 1) : (b = 2);
140 }""")
141
142 def test_casts(self):
143 self._assert_ctoc_correct(r"""
144 int main() {
145 int b = (int) f;
146 int c = (int*) f;
147 }""")
148 self._assert_ctoc_correct(r"""
149 int main() {
150 int a = (int) b + 8;
151 int t = (int) c;
152 }
153 """)
154
155 def test_initlist(self):
156 self._assert_ctoc_correct("int arr[] = {1, 2, 3};")
157
158 def test_exprs(self):
159 self._assert_ctoc_correct("""
160 int main(void)
161 {
162 int a;
163 int b = a++;
164 int c = ++a;
165 int d = a--;
166 int e = --a;
167 }""")
168
169 def test_statements(self):
170 # note two minuses here
171 self._assert_ctoc_correct(r"""
172 int main() {
173 int a;
174 a = 5;
175 ;
176 b = - - a;
177 return a;
178 }""")
179
180 def test_struct_decl(self):
181 self._assert_ctoc_correct(r"""
182 typedef struct node_t {
183 struct node_t* next;
184 int data;
185 } node;
186 """)
187
188 def test_krstyle(self):
189 self._assert_ctoc_correct(r"""
190 int main(argc, argv)
191 int argc;
192 char** argv;
193 {
194 return 0;
195 }
196 """)
197
198 def test_switchcase(self):
199 self._assert_ctoc_correct(r"""
200 int main() {
201 switch (myvar) {
202 case 10:
203 {
204 k = 10;
205 p = k + 1;
206 break;
207 }
208 case 20:
209 case 30:
210 return 20;
211 default:
212 break;
213 }
214 }
215 """)
216
217 def test_nest_initializer_list(self):
218 self._assert_ctoc_correct(r"""
219 int main()
220 {
221 int i[1][1] = { { 1 } };
222 }""")
223
224 def test_nest_named_initializer(self):
225 self._assert_ctoc_correct(r"""struct test
226 {
227 int i;
228 struct test_i_t
229 {
230 int k;
231 } test_i;
232 int j;
233 };
234 struct test test_var = {.i = 0, .test_i = {.k = 1}, .j = 2};
235 """)
236
237 def test_expr_list_in_initializer_list(self):
238 self._assert_ctoc_correct(r"""
239 int main()
240 {
241 int i[1] = { (1, 2) };
242 }""")
243
244 def test_issue36(self):
245 self._assert_ctoc_correct(r"""
246 int main() {
247 }""")
248
249 def test_issue37(self):
250 self._assert_ctoc_correct(r"""
251 int main(void)
252 {
253 unsigned size;
254 size = sizeof(size);
255 return 0;
256 }""")
257
258 def test_issue66(self):
259 # A non-existing body must not be generated
260 # (previous valid behavior, still working)
261 self._assert_ctoc_correct(r"""
262 struct foo;
263 """)
264 # An empty body must be generated
265 # (added behavior)
266 self._assert_ctoc_correct(r"""
267 struct foo {};
268 """)
269
270 def test_issue83(self):
271 self._assert_ctoc_correct(r"""
272 void x(void) {
273 int i = (9, k);
274 }
275 """)
276
277 def test_issue84(self):
278 self._assert_ctoc_correct(r"""
279 void x(void) {
280 for (int i = 0;;)
281 i;
282 }
283 """)
284
285 def test_issue246(self):
286 self._assert_ctoc_correct(r"""
287 int array[3] = {[0] = 0, [1] = 1, [1+1] = 2};
288 """)
289
290 def test_noreturn(self):
291 self._assert_ctoc_correct(r"""
292 _Noreturn int x(void) {
293 abort();
294 }
295 """)
296
297 def test_exprlist_with_semi(self):
298 self._assert_ctoc_correct(r"""
299 void x() {
300 if (i < j)
301 tmp = C[i], C[i] = C[j], C[j] = tmp;
302 if (i <= j)
303 i++, j--;
304 }
305 """)
306
307 def test_exprlist_with_compound(self):
308 self._assert_ctoc_correct(r"""
309 void test(){
310 (sizeof (0), ({ if (0) ; else ; }));
311 }
312 """)
313
314 def test_exprlist_with_subexprlist(self):
315 self._assert_ctoc_correct(r"""
316 void x() {
317 (a = b, (b = c, c = a));
318 }
319 """)
320
321 def test_comma_operator_funcarg(self):
322 self._assert_ctoc_correct(r"""
323 void f(int x) { return x; }
324 int main(void) { f((1, 2)); return 0; }
325 """)
326
327 def test_comma_op_in_ternary(self):
328 self._assert_ctoc_correct(r"""
329 void f() {
330 (0, 0) ? (0, 0) : (0, 0);
331 }
332 """)
333
334 def test_comma_op_assignment(self):
335 self._assert_ctoc_correct(r"""
336 void f() {
337 i = (a, b, c);
338 }
339 """)
340
341 def test_pragma(self):
342 self._assert_ctoc_correct(r"""
343 #pragma foo
344 void f() {
345 #pragma bar
346 i = (a, b, c);
347 if (d)
348 #pragma qux
349 j = e;
350 if (d)
351 #pragma qux
352 #pragma quux
353 j = e;
354 }
355 typedef struct s {
356 #pragma baz
357 } s;
358 """)
359
360 def test_compound_literal(self):
361 self._assert_ctoc_correct('char **foo = (char *[]){ "x", "y", "z" };')
362 self._assert_ctoc_correct("int i = ++(int){ 1 };")
363 self._assert_ctoc_correct("struct foo_s foo = (struct foo_s){ 1, 2 };")
364
365 def test_enum(self):
366 self._assert_ctoc_correct(r"""
367 enum e
368 {
369 a,
370 b = 2,
371 c = 3
372 };
373 """)
374 self._assert_ctoc_correct(r"""
375 enum f
376 {
377 g = 4,
378 h,
379 i
380 };
381 """)
382
383 def test_enum_typedef(self):
384 self._assert_ctoc_correct("typedef enum EnumName EnumTypedefName;")
385
386 def test_generate_struct_union_enum_exception(self):
387 generator = c_generator.CGenerator()
388 self.assertRaises(
389 AssertionError,
390 generator._generate_struct_union_enum,
391 n=c_ast.Struct(
392 name="TestStruct",
393 decls=[],
394 ),
395 name="",
396 )
397
398 def test_array_decl(self):
399 self._assert_ctoc_correct("int g(const int a[const 20]){}")
400 ast = parse_to_ast("const int a[const 20];")
401 generator = c_generator.CGenerator()
402 self.assertEqual(generator.visit(ast.ext[0].type), "const int [const 20]")
403 self.assertEqual(generator.visit(ast.ext[0].type.type), "const int")
404
405 def test_ptr_decl(self):
406 src = "const int ** const x;"
407 self._assert_ctoc_correct(src)
408 ast = parse_to_ast(src)
409 generator = c_generator.CGenerator()
410 self.assertEqual(generator.visit(ast.ext[0].type), "const int ** const")
411 self.assertEqual(generator.visit(ast.ext[0].type.type), "const int *")
412 self.assertEqual(generator.visit(ast.ext[0].type.type.type), "const int")
413
414 def test_atomic_qual(self):
415 self._assert_ctoc_correct("_Atomic int x;")
416 self._assert_ctoc_correct("_Atomic int* x;")
417 self._assert_ctoc_correct("int* _Atomic x;")
418
419 # _Atomic specifier gets turned into qualifier.
420 s1 = "_Atomic(int) x;"
421 c1 = self._run_c_to_c(s1)
422 self.assertEqual(c1, "_Atomic int x;\n")
423 self._assert_ctoc_correct(s1)
424
425 s2 = "_Atomic(int*) x;"
426 c2 = self._run_c_to_c(s2)
427 self.assertEqual(c2, "int * _Atomic x;\n")
428 self._assert_ctoc_correct(s2)
429
430 s3 = "_Atomic(_Atomic(int)*) x;"
431 c3 = self._run_c_to_c(s3)
432 self.assertEqual(c3, "_Atomic int * _Atomic x;\n")
433 self._assert_ctoc_correct(s3)
434
435 # TODO: Regeneration with multiple qualifiers is not fully supported.
436 # REF: https://github.com/eliben/pycparser/issues/433
437 # self._assert_ctoc_correct('auto const _Atomic(int *) a;')
438
439 s4 = "typedef _Atomic(int) atomic_int;"
440 c4 = self._run_c_to_c(s4)
441 self.assertEqual(c4, "typedef _Atomic int atomic_int;\n")
442 self._assert_ctoc_correct(s4)
443
444 s5 = "typedef _Atomic(_Atomic(_Atomic(int (*)(void)) *) *) t;"
445 c5 = self._run_c_to_c(s5)
446 self.assertEqual(c5, "typedef int (* _Atomic * _Atomic * _Atomic t)(void);\n")
447 self._assert_ctoc_correct(s5)
448
449 self._assert_ctoc_correct(r"""
450 typedef struct node_t {
451 _Atomic(void*) a;
452 _Atomic(void) *b;
453 _Atomic void *c;
454 } node;
455 """)
456
457 def test_nested_sizeof(self):
458 src = "1"
459 for _ in range(30):
460 src = "sizeof(" + src + ")"
461 src = "int x = " + src + ";"
462 self._assert_ctoc_correct(src)
463
464 def test_static_assert(self):
465 self._assert_ctoc_correct('_Static_assert(sizeof(int) == sizeof(int), "123");')
466 self._assert_ctoc_correct(
467 'int main() { _Static_assert(sizeof(int) == sizeof(int), "123"); } '
468 )
469 self._assert_ctoc_correct("_Static_assert(sizeof(int) == sizeof(int));")
470
471 def test_reduce_parentheses_binaryops(self):
472 c1 = "int x = a + b + c + d;"
473 self.assertEqual(self._run_c_to_c(c1), "int x = ((a + b) + c) + d;\n")
474 self.assertEqual(
475 self._run_c_to_c(c1, reduce_parentheses=True), "int x = a + b + c + d;\n"
476 )
477
478 # codes with minimum number of (necessary) parenthesis:
479 test_snippets = [
480 "int x = a*b*c*d;",
481 "int x = a+b*c*d;",
482 "int x = a*b+c*d;",
483 "int x = a*b*c+d;",
484 "int x = (a+b)*c*d;",
485 "int x = (a+b)*(c+d);",
486 "int x = (a+b)/(c-d);",
487 "int x = a+b-c-d;",
488 "int x = a+(b-c)-d;",
489 ]
490 for src in test_snippets:
491 src2 = self._assert_ctoc_correct(src, reduce_parentheses=True)
492 self.assertTrue(
493 src2.count("(") == src.count("("),
494 msg="{!r} did not have minimum number of parenthesis, should be like {!r}.".format(
495 src2, src
496 ),
497 )
498
499
500 class TestCasttoC(unittest.TestCase):
501 def _find_file(self, name):
502 test_dir = os.path.dirname(__file__)
503 name = os.path.join(test_dir, "c_files", name)
504 assert os.path.exists(name)
505 return name
506
507 def test_to_type(self):
508 src = "int *x;"
509 generator = c_generator.CGenerator()
510 test_fun = c_ast.FuncCall(c_ast.ID("test_fun"), c_ast.ExprList([]))
511
512 ast1 = parse_to_ast(src)
513 int_ptr_type = ast1.ext[0].type
514 int_type = int_ptr_type.type
515 self.assertEqual(
516 generator.visit(c_ast.Cast(int_ptr_type, test_fun)), "(int *) test_fun()"
517 )
518 self.assertEqual(
519 generator.visit(c_ast.Cast(int_type, test_fun)), "(int) test_fun()"
520 )
521
522 @unittest.skipUnless(cpp_supported(), "cpp only works on Unix")
523 def test_to_type_with_cpp(self):
524 generator = c_generator.CGenerator()
525 test_fun = c_ast.FuncCall(c_ast.ID("test_fun"), c_ast.ExprList([]))
526 memmgr_path = self._find_file("memmgr.h")
527
528 ast2 = parse_file(
529 memmgr_path, use_cpp=True, cpp_path=cpp_path(), cpp_args=cpp_args()
530 )
531 void_ptr_type = ast2.ext[-3].type.type
532 void_type = void_ptr_type.type
533 self.assertEqual(
534 generator.visit(c_ast.Cast(void_ptr_type, test_fun)), "(void *) test_fun()"
535 )
536 self.assertEqual(
537 generator.visit(c_ast.Cast(void_type, test_fun)), "(void) test_fun()"
538 )
539
540 def test_nested_else_if_line_breaks(self):
541 generator = c_generator.CGenerator()
542 test_ast1 = c_ast.If(None, None, None)
543 test_ast2 = c_ast.If(None, None, c_ast.If(None, None, None))
544 test_ast3 = c_ast.If(
545 None, None, c_ast.If(None, None, c_ast.If(None, None, None))
546 )
547 test_ast4 = c_ast.If(
548 None,
549 c_ast.Compound([]),
550 c_ast.If(
551 None, c_ast.Compound([]), c_ast.If(None, c_ast.Compound([]), None)
552 ),
553 )
554
555 self.assertEqual(generator.visit(test_ast1), "if ()\n \n")
556 self.assertEqual(generator.visit(test_ast2), "if ()\n \nelse\n if ()\n \n")
557 self.assertEqual(
558 generator.visit(test_ast3),
559 "if ()\n \nelse\n if ()\n \nelse\n if ()\n \n",
560 )
561 self.assertEqual(
562 generator.visit(test_ast4),
563 "if ()\n{\n}\nelse\n if ()\n{\n}\nelse\n if ()\n{\n}\n",
564 )
565
566
567 if __name__ == "__main__":
568 unittest.main()