blob: e0f8aa3742a5cb9c77d20a32c626fd5ac05ed7c6 [file] [log] [blame]
Hart Chu4771ceb2017-02-21 22:10:36 -06001#-----------------------------------------------------------------
2# pycparser: serialize_ast.py
3#
4# Simple example of serializing AST
5#
6# Hart Chu [https://github.com/CtheSky]
Jon Dufresne1d866992018-06-26 13:49:35 -07007# Eli Bendersky [https://eli.thegreenplace.net/]
Hart Chu4771ceb2017-02-21 22:10:36 -06008# 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.
Hart Chu4771ceb2017-02-21 22:10:36 -060029
Eli Bendersky599a4952017-02-21 20:13:03 -080030with open('ast', 'wb') as f:
31 pickle.dump(ast, f, protocol=-1)
Hart Chu4771ceb2017-02-21 22:10:36 -060032
Eli Bendersky599a4952017-02-21 20:13:03 -080033# Deserialize.
34with open('ast', 'rb') as f:
35 ast = pickle.load(f)
36 ast.show()