Debian Codegraph @

pycparser223/tests/test_c_generator.py

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