| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
from string import Template |
| 14 |
|
| 15 |
|
| 16 |
class ASTCodeGenerator(object): |
| 17 |
def __init__(self, cfg_filename='_c_ast.cfg'): |
| 18 |
""" Initialize the code generator from a configuration |
| 19 |
file. |
| 20 |
""" |
| 21 |
self.cfg_filename = cfg_filename |
| 22 |
self.node_cfg = [NodeCfg(name, contents) |
| 23 |
for (name, contents) in self.parse_cfgfile(cfg_filename)] |
| 24 |
|
| 25 |
def generate(self, file=None): |
| 26 |
""" Generates the code into file, an open file buffer. |
| 27 |
""" |
| 28 |
src = Template(_PROLOGUE_COMMENT).substitute( |
| 29 |
cfg_filename=self.cfg_filename) |
| 30 |
|
| 31 |
src += _PROLOGUE_CODE |
| 32 |
for node_cfg in self.node_cfg: |
| 33 |
src += node_cfg.generate_source() + '\n\n' |
| 34 |
|
| 35 |
file.write(src) |
| 36 |
|
| 37 |
def parse_cfgfile(self, filename): |
| 38 |
""" Parse the configuration file and yield pairs of |
| 39 |
(name, contents) for each node. |
| 40 |
""" |
| 41 |
with open(filename, "r") as f: |
| 42 |
for line in f: |
| 43 |
line = line.strip() |
| 44 |
if not line or line.startswith('#'): |
| 45 |
continue |
| 46 |
colon_i = line.find(':') |
| 47 |
lbracket_i = line.find('[') |
| 48 |
rbracket_i = line.find(']') |
| 49 |
if colon_i < 1 or lbracket_i <= colon_i or rbracket_i <= lbracket_i: |
| 50 |
raise RuntimeError("Invalid line in %s:\n%s\n" % (filename, line)) |
| 51 |
|
| 52 |
name = line[:colon_i] |
| 53 |
val = line[lbracket_i + 1:rbracket_i] |
| 54 |
vallist = [v.strip() for v in val.split(',')] if val else [] |
| 55 |
yield name, vallist |
| 56 |
|
| 57 |
|
| 58 |
class NodeCfg(object): |
| 59 |
""" Node configuration. |
| 60 |
|
| 61 |
name: node name |
| 62 |
contents: a list of contents - attributes and child nodes |
| 63 |
See comment at the top of the configuration file for details. |
| 64 |
""" |
| 65 |
|
| 66 |
def __init__(self, name, contents): |
| 67 |
self.name = name |
| 68 |
self.all_entries = [] |
| 69 |
self.attr = [] |
| 70 |
self.child = [] |
| 71 |
self.seq_child = [] |
| 72 |
|
| 73 |
for entry in contents: |
| 74 |
clean_entry = entry.rstrip('*') |
| 75 |
self.all_entries.append(clean_entry) |
| 76 |
|
| 77 |
if entry.endswith('**'): |
| 78 |
self.seq_child.append(clean_entry) |
| 79 |
elif entry.endswith('*'): |
| 80 |
self.child.append(clean_entry) |
| 81 |
else: |
| 82 |
self.attr.append(entry) |
| 83 |
|
| 84 |
def generate_source(self): |
| 85 |
src = self._gen_init() |
| 86 |
src += '\n' + self._gen_children() |
| 87 |
src += '\n' + self._gen_iter() |
| 88 |
src += '\n' + self._gen_attr_names() |
| 89 |
return src |
| 90 |
|
| 91 |
def _gen_init(self): |
| 92 |
src = "class %s(Node):\n" % self.name |
| 93 |
|
| 94 |
if self.all_entries: |
| 95 |
args = ', '.join(self.all_entries) |
| 96 |
slots = ', '.join("'{0}'".format(e) for e in self.all_entries) |
| 97 |
slots += ", 'coord', '__weakref__'" |
| 98 |
arglist = '(self, %s, coord=None)' % args |
| 99 |
else: |
| 100 |
slots = "'coord', '__weakref__'" |
| 101 |
arglist = '(self, coord=None)' |
| 102 |
|
| 103 |
src += " __slots__ = (%s)\n" % slots |
| 104 |
src += " def __init__%s:\n" % arglist |
| 105 |
|
| 106 |
for name in self.all_entries + ['coord']: |
| 107 |
src += " self.%s = %s\n" % (name, name) |
| 108 |
|
| 109 |
return src |
| 110 |
|
| 111 |
def _gen_children(self): |
| 112 |
src = ' def children(self):\n' |
| 113 |
|
| 114 |
if self.all_entries: |
| 115 |
src += ' nodelist = []\n' |
| 116 |
|
| 117 |
for child in self.child: |
| 118 |
src += ( |
| 119 |
' if self.%(child)s is not None:' + |
| 120 |
' nodelist.append(("%(child)s", self.%(child)s))\n') % ( |
| 121 |
dict(child=child)) |
| 122 |
|
| 123 |
for seq_child in self.seq_child: |
| 124 |
src += ( |
| 125 |
' for i, child in enumerate(self.%(child)s or []):\n' |
| 126 |
' nodelist.append(("%(child)s[%%d]" %% i, child))\n') % ( |
| 127 |
dict(child=seq_child)) |
| 128 |
|
| 129 |
src += ' return tuple(nodelist)\n' |
| 130 |
else: |
| 131 |
src += ' return ()\n' |
| 132 |
|
| 133 |
return src |
| 134 |
|
| 135 |
def _gen_iter(self): |
| 136 |
src = ' def __iter__(self):\n' |
| 137 |
|
| 138 |
if self.all_entries: |
| 139 |
for child in self.child: |
| 140 |
src += ( |
| 141 |
' if self.%(child)s is not None:\n' + |
| 142 |
' yield self.%(child)s\n') % (dict(child=child)) |
| 143 |
|
| 144 |
for seq_child in self.seq_child: |
| 145 |
src += ( |
| 146 |
' for child in (self.%(child)s or []):\n' |
| 147 |
' yield child\n') % (dict(child=seq_child)) |
| 148 |
|
| 149 |
if not (self.child or self.seq_child): |
| 150 |
|
| 151 |
src += ( |
| 152 |
' return\n' + |
| 153 |
' yield\n') |
| 154 |
else: |
| 155 |
|
| 156 |
src += ( |
| 157 |
' return\n' + |
| 158 |
' yield\n') |
| 159 |
|
| 160 |
return src |
| 161 |
|
| 162 |
def _gen_attr_names(self): |
| 163 |
src = " attr_names = (" + ''.join("%r, " % nm for nm in self.attr) + ')' |
| 164 |
return src |
| 165 |
|
| 166 |
|
| 167 |
_PROLOGUE_COMMENT = \ |
| 168 |
r'''#----------------------------------------------------------------- |
| 169 |
# ** ATTENTION ** |
| 170 |
# This code was automatically generated from the file: |
| 171 |
# $cfg_filename |
| 172 |
# |
| 173 |
# Do not modify it directly. Modify the configuration file and |
| 174 |
# run the generator again. |
| 175 |
# ** ** *** ** ** |
| 176 |
# |
| 177 |
# pycparser: c_ast.py |
| 178 |
# |
| 179 |
# AST Node classes. |
| 180 |
# |
| 181 |
# Eli Bendersky [https://eli.thegreenplace.net/] |
| 182 |
# License: BSD |
| 183 |
#----------------------------------------------------------------- |
| 184 |
|
| 185 |
''' |
| 186 |
|
| 187 |
_PROLOGUE_CODE = r''' |
| 188 |
import sys |
| 189 |
|
| 190 |
def _repr(obj): |
| 191 |
""" |
| 192 |
Get the representation of an object, with dedicated pprint-like format for lists. |
| 193 |
""" |
| 194 |
if isinstance(obj, list): |
| 195 |
return '[' + (',\n '.join((_repr(e).replace('\n', '\n ') for e in obj))) + '\n]' |
| 196 |
else: |
| 197 |
return repr(obj) |
| 198 |
|
| 199 |
class Node(object): |
| 200 |
__slots__ = () |
| 201 |
""" Abstract base class for AST nodes. |
| 202 |
""" |
| 203 |
def __repr__(self): |
| 204 |
""" Generates a python representation of the current node |
| 205 |
""" |
| 206 |
result = self.__class__.__name__ + '(' |
| 207 |
|
| 208 |
indent = '' |
| 209 |
separator = '' |
| 210 |
for name in self.__slots__[:-2]: |
| 211 |
result += separator |
| 212 |
result += indent |
| 213 |
result += name + '=' + (_repr(getattr(self, name)).replace('\n', '\n ' + (' ' * (len(name) + len(self.__class__.__name__))))) |
| 214 |
|
| 215 |
separator = ',' |
| 216 |
indent = '\n ' + (' ' * len(self.__class__.__name__)) |
| 217 |
|
| 218 |
result += indent + ')' |
| 219 |
|
| 220 |
return result |
| 221 |
|
| 222 |
def children(self): |
| 223 |
""" A sequence of all children that are Nodes |
| 224 |
""" |
| 225 |
pass |
| 226 |
|
| 227 |
def show(self, buf=sys.stdout, offset=0, attrnames=False, nodenames=False, showcoord=False, _my_node_name=None): |
| 228 |
""" Pretty print the Node and all its attributes and |
| 229 |
children (recursively) to a buffer. |
| 230 |
|
| 231 |
buf: |
| 232 |
Open IO buffer into which the Node is printed. |
| 233 |
|
| 234 |
offset: |
| 235 |
Initial offset (amount of leading spaces) |
| 236 |
|
| 237 |
attrnames: |
| 238 |
True if you want to see the attribute names in |
| 239 |
name=value pairs. False to only see the values. |
| 240 |
|
| 241 |
nodenames: |
| 242 |
True if you want to see the actual node names |
| 243 |
within their parents. |
| 244 |
|
| 245 |
showcoord: |
| 246 |
Do you want the coordinates of each Node to be |
| 247 |
displayed. |
| 248 |
""" |
| 249 |
lead = ' ' * offset |
| 250 |
if nodenames and _my_node_name is not None: |
| 251 |
buf.write(lead + self.__class__.__name__+ ' <' + _my_node_name + '>: ') |
| 252 |
else: |
| 253 |
buf.write(lead + self.__class__.__name__+ ': ') |
| 254 |
|
| 255 |
if self.attr_names: |
| 256 |
if attrnames: |
| 257 |
nvlist = [(n, getattr(self,n)) for n in self.attr_names] |
| 258 |
attrstr = ', '.join('%s=%s' % nv for nv in nvlist) |
| 259 |
else: |
| 260 |
vlist = [getattr(self, n) for n in self.attr_names] |
| 261 |
attrstr = ', '.join('%s' % v for v in vlist) |
| 262 |
buf.write(attrstr) |
| 263 |
|
| 264 |
if showcoord: |
| 265 |
buf.write(' (at %s)' % self.coord) |
| 266 |
buf.write('\n') |
| 267 |
|
| 268 |
for (child_name, child) in self.children(): |
| 269 |
child.show( |
| 270 |
buf, |
| 271 |
offset=offset + 2, |
| 272 |
attrnames=attrnames, |
| 273 |
nodenames=nodenames, |
| 274 |
showcoord=showcoord, |
| 275 |
_my_node_name=child_name) |
| 276 |
|
| 277 |
|
| 278 |
class NodeVisitor(object): |
| 279 |
""" A base NodeVisitor class for visiting c_ast nodes. |
| 280 |
Subclass it and define your own visit_XXX methods, where |
| 281 |
XXX is the class name you want to visit with these |
| 282 |
methods. |
| 283 |
|
| 284 |
For example: |
| 285 |
|
| 286 |
class ConstantVisitor(NodeVisitor): |
| 287 |
def __init__(self): |
| 288 |
self.values = [] |
| 289 |
|
| 290 |
def visit_Constant(self, node): |
| 291 |
self.values.append(node.value) |
| 292 |
|
| 293 |
Creates a list of values of all the constant nodes |
| 294 |
encountered below the given node. To use it: |
| 295 |
|
| 296 |
cv = ConstantVisitor() |
| 297 |
cv.visit(node) |
| 298 |
|
| 299 |
Notes: |
| 300 |
|
| 301 |
* generic_visit() will be called for AST nodes for which |
| 302 |
no visit_XXX method was defined. |
| 303 |
* The children of nodes for which a visit_XXX was |
| 304 |
defined will not be visited - if you need this, call |
| 305 |
generic_visit() on the node. |
| 306 |
You can use: |
| 307 |
NodeVisitor.generic_visit(self, node) |
| 308 |
* Modeled after Python's own AST visiting facilities |
| 309 |
(the ast module of Python 3.0) |
| 310 |
""" |
| 311 |
|
| 312 |
_method_cache = None |
| 313 |
|
| 314 |
def visit(self, node): |
| 315 |
""" Visit a node. |
| 316 |
""" |
| 317 |
|
| 318 |
if self._method_cache is None: |
| 319 |
self._method_cache = {} |
| 320 |
|
| 321 |
visitor = self._method_cache.get(node.__class__.__name__, None) |
| 322 |
if visitor is None: |
| 323 |
method = 'visit_' + node.__class__.__name__ |
| 324 |
visitor = getattr(self, method, self.generic_visit) |
| 325 |
self._method_cache[node.__class__.__name__] = visitor |
| 326 |
|
| 327 |
return visitor(node) |
| 328 |
|
| 329 |
def generic_visit(self, node): |
| 330 |
""" Called if no explicit visitor function exists for a |
| 331 |
node. Implements preorder visiting of the node. |
| 332 |
""" |
| 333 |
for c in node: |
| 334 |
self.visit(c) |
| 335 |
|
| 336 |
''' |