Hart Chu | 4771ceb | 2017-02-21 22:10:36 -0600 | [diff] [blame] | 1 | #----------------------------------------------------------------- |
| 2 | # pycparser: serialize_ast.py |
| 3 | # |
| 4 | # Simple example of serializing AST |
| 5 | # |
| 6 | # Hart Chu [https://github.com/CtheSky] |
Jon Dufresne | 1d86699 | 2018-06-26 13:49:35 -0700 | [diff] [blame] | 7 | # Eli Bendersky [https://eli.thegreenplace.net/] |
Hart Chu | 4771ceb | 2017-02-21 22:10:36 -0600 | [diff] [blame] | 8 | # License: BSD |
| 9 | #----------------------------------------------------------------- |
| 10 | from __future__ import print_function |
| 11 | import pickle |
| 12 | |
| 13 | from pycparser import c_parser |
| 14 | |
| 15 | text = r""" |
| 16 | void func(void) |
| 17 | { |
| 18 | x = 1; |
| 19 | } |
| 20 | """ |
| 21 | |
| 22 | parser = c_parser.CParser() |
| 23 | ast = 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 Chu | 4771ceb | 2017-02-21 22:10:36 -0600 | [diff] [blame] | 29 | |
Eli Bendersky | 599a495 | 2017-02-21 20:13:03 -0800 | [diff] [blame] | 30 | with open('ast', 'wb') as f: |
| 31 | pickle.dump(ast, f, protocol=-1) |
Hart Chu | 4771ceb | 2017-02-21 22:10:36 -0600 | [diff] [blame] | 32 | |
Eli Bendersky | 599a495 | 2017-02-21 20:13:03 -0800 | [diff] [blame] | 33 | # Deserialize. |
| 34 | with open('ast', 'rb') as f: |
| 35 | ast = pickle.load(f) |
| 36 | ast.show() |