| 1 | #----------------------------------------------------------------- |
| 2 | # pycparser: serialize_ast.py |
| 3 | # |
| 4 | # Simple example of serializing AST |
| 5 | # |
| 6 | # Hart Chu [https://github.com/CtheSky] |
| 7 | # Eli Bendersky [https://eli.thegreenplace.net/] |
| 8 | # License: BSD |
| 9 | #----------------------------------------------------------------- |
| 10 | import pickle |
| 11 | import sys |
| 12 | |
| 13 | sys.path.extend(['.', '..']) |
| 14 | from pycparser import c_parser |
| 15 | |
| 16 | text = r""" |
| 17 | void func(void) |
| 18 | { |
| 19 | x = 1; |
| 20 | } |
| 21 | """ |
| 22 | |
| 23 | if __name__ == '__main__': |
| 24 | parser = c_parser.CParser() |
| 25 | ast = parser.parse(text) |
| 26 | dump_filename = 'ast.pickle' |
| 27 | |
| 28 | with open(dump_filename, 'wb') as f: |
| 29 | pickle.dump(ast, f, protocol=pickle.HIGHEST_PROTOCOL) |
| 30 | |
| 31 | # Deserialize. |
| 32 | with open(dump_filename, 'rb') as f: |
| 33 | ast = pickle.load(f) |
| 34 | ast.show() |