_ast_gen.py 11 KB

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