blob: eae0cce8f2135dfd60f481fd05ac1517a30ed469 [file] [log] [blame]
eli.bendersky8e6c5862011-05-20 12:35:08 +03001#!/usr/bin/env python
2
3import sys
4import unittest
5
6sys.path.insert(0, '..') # for c-to-c.py
7sys.path.insert(0, '../..') # for pycparser libs
8
9from pycparser import c_parser
10c2cmodule = __import__('c-to-c')
11
12_c_parser = c_parser.CParser(
13 lex_optimize=False,
14 yacc_debug=True,
15 yacc_optimize=False,
16 yacctab='yacctab')
17
18
19def compare_asts(ast1, ast2):
20 if type(ast1) != type(ast2):
21 return False
22 for attr in ast1.attr_names:
23 if getattr(ast1, attr) != getattr(ast2, attr):
24 return False
25 for i, c1 in enumerate(ast1.children()):
26 if compare_asts(c1, ast2.children()[i]) == False:
27 return False
28 return True
29
30
31def parse_to_ast(src):
32 return _c_parser.parse(src)
33
34
35class TestCtoC(unittest.TestCase):
36 def _run_c_to_c(self, src):
37 ast = parse_to_ast(src)
38 generator = c2cmodule.CGenerator()
39 return generator.visit(ast)
40
41 def _assert_ctoc_correct(self, src):
42 """ Checks that the c2c translation was correct by parsing the code
43 generated by c2c for src and comparing the AST with the original
44 AST.
45 """
46 src2 = self._run_c_to_c(src)
47 self.assertTrue(compare_asts(parse_to_ast(src), parse_to_ast(src2)), src2)
48
49 def test_trivial_decls(self):
50 self._assert_ctoc_correct('int a;')
51 self._assert_ctoc_correct('int b, a;')
52 self._assert_ctoc_correct('int c, b, a;')
53
54 def test_complex_decls(self):
55 self._assert_ctoc_correct('int** (*a)(void);')
56 self._assert_ctoc_correct('int** (*a)(void*, int);')
57
58 def test_casts(self):
59 self._assert_ctoc_correct(r'''
60 int main() {
61 int b = (int) f;
62 int c = (int*) f;
63 }''')
64
65 def test_initlist(self):
66 self._assert_ctoc_correct('int arr[] = {1, 2, 3};')
67
68 def test_statements(self):
69 self._assert_ctoc_correct(r'''
70 int main() {
71 int a;
72 a = 5;
73 return a;
74 }''')
eli.benderskycad1cfd2011-05-26 06:56:27 +030075
76 def test_issue36(self):
77 self._assert_ctoc_correct(r'''
78 int main() {
79 }''')
eli.bendersky8e6c5862011-05-20 12:35:08 +030080
81
82
83if __name__ == "__main__":
84 unittest.main()