| 1 | #------------------------------------------------------------------------------ |
| 2 | # pycparser: c-to-c.py |
| 3 | # |
| 4 | # Example of using pycparser.c_generator, serving as a simplistic translator |
| 5 | # from C to AST and back to C. |
| 6 | # |
| 7 | # Eli Bendersky [https://eli.thegreenplace.net/] |
| 8 | # License: BSD |
| 9 | #------------------------------------------------------------------------------ |
| 10 | import sys |
| 11 | |
| 12 | # This is not required if you've installed pycparser into |
| 13 | # your site-packages/ with setup.py |
| 14 | sys.path.extend(['.', '..']) |
| 15 | |
| 16 | from pycparser import parse_file, c_generator |
| 17 | |
| 18 | |
| 19 | def translate_to_c(filename): |
| 20 | """ Simply use the c_generator module to emit a parsed AST. |
| 21 | """ |
| 22 | ast = parse_file(filename, use_cpp=True) |
| 23 | generator = c_generator.CGenerator() |
| 24 | print(generator.visit(ast)) |
| 25 | |
| 26 | |
| 27 | if __name__ == "__main__": |
| 28 | if len(sys.argv) > 1: |
| 29 | translate_to_c(sys.argv[1]) |
| 30 | else: |
| 31 | print("Please provide a filename as argument") |