Debian Codegraph @

pycparser223/examples/c_json.py

raw symbols SCIP
1 #------------------------------------------------------------------------------
2 # pycparser: c_json.py
3 #
4 # by Michael White (@mypalmike)
5 #
6 # This example includes functions to serialize and deserialize an ast
7 # to and from json format. Serializing involves walking the ast and converting
8 # each node from a python Node object into a python dict. Deserializing
9 # involves the opposite conversion, walking the tree formed by the
10 # dict and converting each dict into the specific Node object it represents.
11 # The dict itself is serialized and deserialized using the python json module.
12 #
13 # The dict representation is a fairly direct transformation of the object
14 # attributes. Each node in the dict gets one metadata field referring to the
15 # specific node class name, _nodetype. Each local attribute (i.e. not linking
16 # to child nodes) has a string value or array of string values. Each child
17 # attribute is either another dict or an array of dicts, exactly as in the
18 # Node object representation. The "coord" attribute, representing the
19 # node's location within the source code, is serialized/deserialized from
20 # a Coord object into a string of the format "filename:line[:column]".
21 #
22 # Example TypeDecl node, with IdentifierType child node, represented as a dict:
23 # "type": {
24 # "_nodetype": "TypeDecl",
25 # "coord": "c_files/funky.c:8",
26 # "declname": "o",
27 # "quals": [],
28 # "type": {
29 # "_nodetype": "IdentifierType",
30 # "coord": "c_files/funky.c:8",
31 # "names": [
32 # "char"
33 # ]
34 # }
35 # }
36 #------------------------------------------------------------------------------
37 import json
38 import sys
39 import re
40
41 # This is not required if you've installed pycparser into
42 # your site-packages/ with setup.py
43 sys.path.extend(['.', '..'])
44
45 from pycparser import parse_file, c_ast
46 from pycparser.plyparser import Coord
47
48
49 RE_CHILD_ARRAY = re.compile(r'(.*)\[(.*)\]')
50 RE_INTERNAL_ATTR = re.compile('__.*__')
51
52
53 class CJsonError(Exception):
54 pass
55
56
57 def memodict(fn):
58 """ Fast memoization decorator for a function taking a single argument """
59 class memodict(dict):
60 def __missing__(self, key):
61 ret = self[key] = fn(key)
62 return ret
63 return memodict().__getitem__
64
65
66 @memodict
67 def child_attrs_of(klass):
68 """
69 Given a Node class, get a set of child attrs.
70 Memoized to avoid highly repetitive string manipulation
71
72 """
73 non_child_attrs = set(klass.attr_names)
74 all_attrs = set([i for i in klass.__slots__ if not RE_INTERNAL_ATTR.match(i)])
75 return all_attrs - non_child_attrs
76
77
78 def to_dict(node):
79 """ Recursively convert an ast into dict representation. """
80 klass = node.__class__
81
82 result = {}
83
84 # Metadata
85 result['_nodetype'] = klass.__name__
86
87 # Local node attributes
88 for attr in klass.attr_names:
89 result[attr] = getattr(node, attr)
90
91 # Coord object
92 if node.coord:
93 result['coord'] = str(node.coord)
94 else:
95 result['coord'] = None
96
97 # Child attributes
98 for child_name, child in node.children():
99 # Child strings are either simple (e.g. 'value') or arrays (e.g. 'block_items[1]')
100 match = RE_CHILD_ARRAY.match(child_name)
101 if match:
102 array_name, array_index = match.groups()
103 array_index = int(array_index)
104 # arrays come in order, so we verify and append.
105 result[array_name] = result.get(array_name, [])
106 if array_index != len(result[array_name]):
107 raise CJsonError('Internal ast error. Array {} out of order. '
108 'Expected index {}, got {}'.format(
109 array_name, len(result[array_name]), array_index))
110 result[array_name].append(to_dict(child))
111 else:
112 result[child_name] = to_dict(child)
113
114 # Any child attributes that were missing need "None" values in the json.
115 for child_attr in child_attrs_of(klass):
116 if child_attr not in result:
117 result[child_attr] = None
118
119 return result
120
121
122 def to_json(node, **kwargs):
123 """ Convert ast node to json string """
124 return json.dumps(to_dict(node), **kwargs)
125
126
127 def file_to_dict(filename):
128 """ Load C file into dict representation of ast """
129 ast = parse_file(filename, use_cpp=True)
130 return to_dict(ast)
131
132
133 def file_to_json(filename, **kwargs):
134 """ Load C file into json string representation of ast """
135 ast = parse_file(filename, use_cpp=True)
136 return to_json(ast, **kwargs)
137
138
139 def _parse_coord(coord_str):
140 """ Parse coord string (file:line[:column]) into Coord object. """
141 if coord_str is None:
142 return None
143
144 vals = coord_str.split(':')
145 vals.extend([None] * 3)
146 filename, line, column = vals[:3]
147 return Coord(filename, line, column)
148
149
150 def _convert_to_obj(value):
151 """
152 Convert an object in the dict representation into an object.
153 Note: Mutually recursive with from_dict.
154
155 """
156 value_type = type(value)
157 if value_type == dict:
158 return from_dict(value)
159 elif value_type == list:
160 return [_convert_to_obj(item) for item in value]
161 else:
162 # String
163 return value
164
165
166 def from_dict(node_dict):
167 """ Recursively build an ast from dict representation """
168 class_name = node_dict.pop('_nodetype')
169
170 klass = getattr(c_ast, class_name)
171
172 # Create a new dict containing the key-value pairs which we can pass
173 # to node constructors.
174 objs = {}
175 for key, value in node_dict.items():
176 if key == 'coord':
177 objs[key] = _parse_coord(value)
178 else:
179 objs[key] = _convert_to_obj(value)
180
181 # Use keyword parameters, which works thanks to beautifully consistent
182 # ast Node initializers.
183 return klass(**objs)
184
185
186 def from_json(ast_json):
187 """ Build an ast from json string representation """
188 return from_dict(json.loads(ast_json))
189
190
191 #------------------------------------------------------------------------------
192 if __name__ == "__main__":
193 if len(sys.argv) > 1:
194 # Some test code...
195 # Do trip from C -> ast -> dict -> ast -> json, then print.
196 ast_dict = file_to_dict(sys.argv[1])
197 ast = from_dict(ast_dict)
198 print(to_json(ast, sort_keys=True, indent=4))
199 else:
200 print("Please provide a filename as argument")