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#----------------------------------------------------------------- 10from __future__ import print_function 11import pickle 12 13from pycparser import c_parser 14 15text = r""" 16void func(void) 17{ 18 x = 1; 19} 20""" 21 22parser = c_parser.CParser() 23ast = parser.parse(text) 24 25# Since AST nodes use __slots__ for faster attribute access and 26# space saving, it needs Pickle's protocol version >= 2. 27# The default version is 3 for python 3.x and 1 for python 2.7. 28# You can always select the highest available protocol with the -1 argument. 29 30with open('ast', 'wb') as f: 31 pickle.dump(ast, f, protocol=-1) 32 33# Deserialize. 34with open('ast', 'rb') as f: 35 ast = pickle.load(f) 36 ast.show() 37