c_generator.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. # ------------------------------------------------------------------------------
  2. # pycparser: c_generator.py
  3. #
  4. # C code generator from pycparser AST nodes.
  5. #
  6. # Eli Bendersky [https://eli.thegreenplace.net/]
  7. # License: BSD
  8. # ------------------------------------------------------------------------------
  9. from collections.abc import Callable
  10. from typing import ClassVar
  11. from . import c_ast
  12. class CGenerator:
  13. """Uses the same visitor pattern as c_ast.NodeVisitor, but modified to
  14. return a value from each visit method, using string accumulation in
  15. generic_visit.
  16. """
  17. indent_level: int
  18. reduce_parentheses: bool
  19. def __init__(self, reduce_parentheses: bool = False) -> None:
  20. """Constructs C-code generator
  21. reduce_parentheses:
  22. if True, eliminates needless parentheses on binary operators
  23. """
  24. # Statements start with indentation of self.indent_level spaces, using
  25. # the _make_indent method.
  26. self.indent_level = 0
  27. self.reduce_parentheses = reduce_parentheses
  28. def _make_indent(self) -> str:
  29. return " " * self.indent_level
  30. def visit(self, node: c_ast.Node) -> str:
  31. method = "visit_" + node.__class__.__name__
  32. return getattr(self, method, self.generic_visit)(node)
  33. def generic_visit(self, node: c_ast.Node | None) -> str:
  34. if node is None:
  35. return ""
  36. else:
  37. return "".join(self.visit(c) for c_name, c in node.children())
  38. def visit_Constant(self, n: c_ast.Constant) -> str:
  39. return n.value
  40. def visit_ID(self, n: c_ast.ID) -> str:
  41. return n.name
  42. def visit_Pragma(self, n: c_ast.Pragma) -> str:
  43. ret = "#pragma"
  44. if n.string:
  45. ret += " " + n.string
  46. return ret
  47. def visit_ArrayRef(self, n: c_ast.ArrayRef) -> str:
  48. arrref = self._parenthesize_unless_simple(n.name)
  49. return arrref + "[" + self.visit(n.subscript) + "]"
  50. def visit_StructRef(self, n: c_ast.StructRef) -> str:
  51. sref = self._parenthesize_unless_simple(n.name)
  52. return sref + n.type + self.visit(n.field)
  53. def visit_FuncCall(self, n: c_ast.FuncCall) -> str:
  54. fref = self._parenthesize_unless_simple(n.name)
  55. args = self.visit(n.args) if n.args is not None else ""
  56. return fref + "(" + args + ")"
  57. def visit_GenericSelection(self, n: c_ast.GenericSelection) -> str:
  58. # The controlling and association expressions are assignment-expressions:
  59. # preserve parentheses around comma expressions with _visit_expr.
  60. expr = self._visit_expr(n.expr)
  61. associations = ", ".join(self.visit(a) for a in n.associations)
  62. return f"_Generic({expr}, {associations})"
  63. def visit_GenericAssociation(self, n: c_ast.GenericAssociation) -> str:
  64. typ = self.visit(n.type) if n.type is not None else "default"
  65. return f"{typ}: {self._visit_expr(n.expr)}"
  66. def visit_UnaryOp(self, n: c_ast.UnaryOp) -> str:
  67. match n.op:
  68. case "sizeof":
  69. # Always parenthesize the argument of sizeof since it can be
  70. # a name.
  71. return f"sizeof({self.visit(n.expr)})"
  72. case "p++":
  73. operand = self._parenthesize_unless_simple(n.expr)
  74. return f"{operand}++"
  75. case "p--":
  76. operand = self._parenthesize_unless_simple(n.expr)
  77. return f"{operand}--"
  78. case _:
  79. operand = self._parenthesize_unless_simple(n.expr)
  80. return f"{n.op}{operand}"
  81. # Precedence map of binary operators:
  82. precedence_map: ClassVar[dict[str, int]] = {
  83. # Should be in sync with c_parser.CParser.precedence
  84. # Higher numbers are stronger binding
  85. "||": 0, # weakest binding
  86. "&&": 1,
  87. "|": 2,
  88. "^": 3,
  89. "&": 4,
  90. "==": 5,
  91. "!=": 5,
  92. ">": 6,
  93. ">=": 6,
  94. "<": 6,
  95. "<=": 6,
  96. ">>": 7,
  97. "<<": 7,
  98. "+": 8,
  99. "-": 8,
  100. "*": 9,
  101. "/": 9,
  102. "%": 9, # strongest binding
  103. }
  104. def visit_BinaryOp(self, n: c_ast.BinaryOp) -> str:
  105. # Note: all binary operators are left-to-right associative
  106. #
  107. # If `n.left.op` has a stronger or equally binding precedence in
  108. # comparison to `n.op`, no parenthesis are needed for the left:
  109. # e.g., `(a*b) + c` is equivalent to `a*b + c`, as well as
  110. # `(a+b) - c` is equivalent to `a+b - c` (same precedence).
  111. # If the left operator is weaker binding than the current, then
  112. # parentheses are necessary:
  113. # e.g., `(a+b) * c` is NOT equivalent to `a+b * c`.
  114. lval_str = self._parenthesize_if(
  115. n.left,
  116. lambda d: (
  117. not (
  118. self._is_simple_node(d)
  119. or self.reduce_parentheses
  120. and isinstance(d, c_ast.BinaryOp)
  121. and self.precedence_map[d.op] >= self.precedence_map[n.op]
  122. )
  123. ),
  124. )
  125. # If `n.right.op` has a stronger -but not equal- binding precedence,
  126. # parenthesis can be omitted on the right:
  127. # e.g., `a + (b*c)` is equivalent to `a + b*c`.
  128. # If the right operator is weaker or equally binding, then parentheses
  129. # are necessary:
  130. # e.g., `a * (b+c)` is NOT equivalent to `a * b+c` and
  131. # `a - (b+c)` is NOT equivalent to `a - b+c` (same precedence).
  132. rval_str = self._parenthesize_if(
  133. n.right,
  134. lambda d: (
  135. not (
  136. self._is_simple_node(d)
  137. or self.reduce_parentheses
  138. and isinstance(d, c_ast.BinaryOp)
  139. and self.precedence_map[d.op] > self.precedence_map[n.op]
  140. )
  141. ),
  142. )
  143. return f"{lval_str} {n.op} {rval_str}"
  144. def visit_Assignment(self, n: c_ast.Assignment) -> str:
  145. rval_str = self._parenthesize_if(
  146. n.rvalue, lambda n: isinstance(n, c_ast.Assignment)
  147. )
  148. return f"{self.visit(n.lvalue)} {n.op} {rval_str}"
  149. def visit_IdentifierType(self, n: c_ast.IdentifierType) -> str:
  150. return " ".join(n.names)
  151. def _visit_expr(self, n: c_ast.Node) -> str:
  152. match n:
  153. case c_ast.InitList():
  154. return "{" + self.visit(n) + "}"
  155. case c_ast.ExprList() | c_ast.Compound():
  156. return "(" + self.visit(n) + ")"
  157. case _:
  158. return self.visit(n)
  159. def visit_Decl(self, n: c_ast.Decl, no_type: bool = False) -> str:
  160. # Later declarations in a DeclList omit the shared specifiers, but
  161. # still need their own pointer, array, and function declarator parts.
  162. s = (
  163. self._generate_type(n.type, emit_base_type=False)
  164. if no_type
  165. else self._generate_decl(n)
  166. )
  167. if n.bitsize:
  168. s += " : " + self.visit(n.bitsize)
  169. if n.init:
  170. s += " = " + self._visit_expr(n.init)
  171. return s
  172. def visit_DeclList(self, n: c_ast.DeclList) -> str:
  173. s = self.visit(n.decls[0])
  174. if len(n.decls) > 1:
  175. s += ", " + ", ".join(
  176. self.visit_Decl(decl, no_type=True) for decl in n.decls[1:]
  177. )
  178. return s
  179. def visit_Typedef(self, n: c_ast.Typedef) -> str:
  180. s = ""
  181. if n.storage:
  182. s += " ".join(n.storage) + " "
  183. s += self._generate_type(n.type)
  184. return s
  185. def visit_Cast(self, n: c_ast.Cast) -> str:
  186. s = "(" + self._generate_type(n.to_type, emit_declname=False) + ")"
  187. return s + " " + self._parenthesize_unless_simple(n.expr)
  188. def visit_ExprList(self, n: c_ast.ExprList) -> str:
  189. visited_subexprs = []
  190. for expr in n.exprs:
  191. visited_subexprs.append(self._visit_expr(expr))
  192. return ", ".join(visited_subexprs)
  193. def visit_InitList(self, n: c_ast.InitList) -> str:
  194. visited_subexprs = []
  195. for expr in n.exprs:
  196. visited_subexprs.append(self._visit_expr(expr))
  197. return ", ".join(visited_subexprs)
  198. def visit_Enum(self, n: c_ast.Enum) -> str:
  199. return self._generate_struct_union_enum(n, name="enum")
  200. def visit_Alignas(self, n: c_ast.Alignas) -> str:
  201. return f"_Alignas({self.visit(n.alignment)})"
  202. def visit_Enumerator(self, n: c_ast.Enumerator) -> str:
  203. if not n.value:
  204. return f"{self._make_indent()}{n.name},\n"
  205. else:
  206. return f"{self._make_indent()}{n.name} = {self.visit(n.value)},\n"
  207. def visit_FuncDef(self, n: c_ast.FuncDef) -> str:
  208. decl = self.visit(n.decl)
  209. self.indent_level = 0
  210. body = self.visit(n.body)
  211. if n.param_decls:
  212. knrdecls = ";\n".join(self.visit(p) for p in n.param_decls)
  213. return decl + "\n" + knrdecls + ";\n" + body + "\n"
  214. else:
  215. return decl + "\n" + body + "\n"
  216. def visit_FileAST(self, n: c_ast.FileAST) -> str:
  217. s = ""
  218. for ext in n.ext:
  219. match ext:
  220. case c_ast.FuncDef():
  221. s += self.visit(ext)
  222. case c_ast.Pragma():
  223. s += self.visit(ext) + "\n"
  224. case _:
  225. s += self.visit(ext) + ";\n"
  226. return s
  227. def visit_Compound(self, n: c_ast.Compound) -> str:
  228. s = self._make_indent() + "{\n"
  229. self.indent_level += 2
  230. if n.block_items:
  231. s += "".join(self._generate_stmt(stmt) for stmt in n.block_items)
  232. self.indent_level -= 2
  233. s += self._make_indent() + "}\n"
  234. return s
  235. def visit_CompoundLiteral(self, n: c_ast.CompoundLiteral) -> str:
  236. return "(" + self.visit(n.type) + "){" + self.visit(n.init) + "}"
  237. def visit_EmptyStatement(self, n: c_ast.EmptyStatement) -> str:
  238. return ";"
  239. def visit_ParamList(self, n: c_ast.ParamList) -> str:
  240. return ", ".join(self.visit(param) for param in n.params)
  241. def visit_Return(self, n: c_ast.Return) -> str:
  242. s = "return"
  243. if n.expr:
  244. s += " " + self.visit(n.expr)
  245. return s + ";"
  246. def visit_Break(self, n: c_ast.Break) -> str:
  247. return "break;"
  248. def visit_Continue(self, n: c_ast.Continue) -> str:
  249. return "continue;"
  250. def visit_TernaryOp(self, n: c_ast.TernaryOp) -> str:
  251. s = "(" + self._visit_expr(n.cond) + ") ? "
  252. s += "(" + self._visit_expr(n.iftrue) + ") : "
  253. s += "(" + self._visit_expr(n.iffalse) + ")"
  254. return s
  255. def visit_If(self, n: c_ast.If) -> str:
  256. s = "if ("
  257. if n.cond:
  258. s += self.visit(n.cond)
  259. s += ")\n"
  260. s += self._generate_stmt(n.iftrue, add_indent=True)
  261. if n.iffalse:
  262. s += self._make_indent() + "else\n"
  263. s += self._generate_stmt(n.iffalse, add_indent=True)
  264. return s
  265. def visit_For(self, n: c_ast.For) -> str:
  266. s = "for ("
  267. if n.init:
  268. s += self.visit(n.init)
  269. s += ";"
  270. if n.cond:
  271. s += " " + self.visit(n.cond)
  272. s += ";"
  273. if n.next:
  274. s += " " + self.visit(n.next)
  275. s += ")\n"
  276. s += self._generate_stmt(n.stmt, add_indent=True)
  277. return s
  278. def visit_While(self, n: c_ast.While) -> str:
  279. s = "while ("
  280. if n.cond:
  281. s += self.visit(n.cond)
  282. s += ")\n"
  283. s += self._generate_stmt(n.stmt, add_indent=True)
  284. return s
  285. def visit_DoWhile(self, n: c_ast.DoWhile) -> str:
  286. s = "do\n"
  287. s += self._generate_stmt(n.stmt, add_indent=True)
  288. s += self._make_indent() + "while ("
  289. if n.cond:
  290. s += self.visit(n.cond)
  291. s += ");"
  292. return s
  293. def visit_StaticAssert(self, n: c_ast.StaticAssert) -> str:
  294. s = "_Static_assert("
  295. s += self.visit(n.cond)
  296. if n.message:
  297. s += ", "
  298. s += self.visit(n.message)
  299. s += ")"
  300. return s
  301. def visit_Switch(self, n: c_ast.Switch) -> str:
  302. s = "switch (" + self.visit(n.cond) + ")\n"
  303. s += self._generate_stmt(n.stmt, add_indent=True)
  304. return s
  305. def visit_Case(self, n: c_ast.Case) -> str:
  306. s = "case " + self.visit(n.expr) + ":\n"
  307. for stmt in n.stmts:
  308. s += self._generate_stmt(stmt, add_indent=True)
  309. return s
  310. def visit_Default(self, n: c_ast.Default) -> str:
  311. s = "default:\n"
  312. for stmt in n.stmts:
  313. s += self._generate_stmt(stmt, add_indent=True)
  314. return s
  315. def visit_Label(self, n: c_ast.Label) -> str:
  316. return n.name + ":\n" + self._generate_stmt(n.stmt)
  317. def visit_Goto(self, n: c_ast.Goto) -> str:
  318. return "goto " + n.name + ";"
  319. def visit_EllipsisParam(self, n: c_ast.EllipsisParam) -> str:
  320. return "..."
  321. def visit_Struct(self, n: c_ast.Struct) -> str:
  322. return self._generate_struct_union_enum(n, "struct")
  323. def visit_Typename(self, n: c_ast.Typename) -> str:
  324. return self._generate_type(n.type)
  325. def visit_Union(self, n: c_ast.Union) -> str:
  326. return self._generate_struct_union_enum(n, "union")
  327. def visit_NamedInitializer(self, n: c_ast.NamedInitializer) -> str:
  328. s = ""
  329. for name in n.name:
  330. if isinstance(name, c_ast.ID):
  331. s += "." + name.name
  332. else:
  333. s += "[" + self.visit(name) + "]"
  334. s += " = " + self._visit_expr(n.expr)
  335. return s
  336. def visit_FuncDecl(self, n: c_ast.FuncDecl) -> str:
  337. return self._generate_type(n)
  338. def visit_ArrayDecl(self, n: c_ast.ArrayDecl) -> str:
  339. return self._generate_type(n, emit_declname=False)
  340. def visit_TypeDecl(self, n: c_ast.TypeDecl) -> str:
  341. return self._generate_type(n, emit_declname=False)
  342. def visit_PtrDecl(self, n: c_ast.PtrDecl) -> str:
  343. return self._generate_type(n, emit_declname=False)
  344. def _generate_struct_union_enum(
  345. self, n: c_ast.Struct | c_ast.Union | c_ast.Enum, name: str
  346. ) -> str:
  347. """Generates code for structs, unions, and enums. name should be
  348. 'struct', 'union', or 'enum'.
  349. """
  350. if name in ("struct", "union"):
  351. assert isinstance(n, (c_ast.Struct, c_ast.Union))
  352. members = n.decls
  353. body_function = self._generate_struct_union_body
  354. else:
  355. assert name == "enum"
  356. assert isinstance(n, c_ast.Enum)
  357. members = None if n.values is None else n.values.enumerators
  358. body_function = self._generate_enum_body
  359. s = name + " " + (n.name or "")
  360. if members is not None:
  361. # None means no members
  362. # Empty sequence means an empty list of members
  363. s += "\n"
  364. s += self._make_indent()
  365. self.indent_level += 2
  366. s += "{\n"
  367. s += body_function(members)
  368. self.indent_level -= 2
  369. s += self._make_indent() + "}"
  370. return s
  371. def _generate_struct_union_body(self, members: list[c_ast.Node]) -> str:
  372. return "".join(self._generate_stmt(decl) for decl in members)
  373. def _generate_enum_body(self, members: list[c_ast.Enumerator]) -> str:
  374. # `[:-2] + '\n'` removes the final `,` from the enumerator list
  375. return "".join(self.visit(value) for value in members)[:-2] + "\n"
  376. def _generate_stmt(self, n: c_ast.Node, add_indent: bool = False) -> str:
  377. """Generation from a statement node. This method exists as a wrapper
  378. for individual visit_* methods to handle different treatment of
  379. some statements in this context.
  380. """
  381. if add_indent:
  382. self.indent_level += 2
  383. indent = self._make_indent()
  384. if add_indent:
  385. self.indent_level -= 2
  386. match n:
  387. case (
  388. c_ast.Decl()
  389. | c_ast.Assignment()
  390. | c_ast.Cast()
  391. | c_ast.UnaryOp()
  392. | c_ast.BinaryOp()
  393. | c_ast.TernaryOp()
  394. | c_ast.FuncCall()
  395. | c_ast.ArrayRef()
  396. | c_ast.StructRef()
  397. | c_ast.Constant()
  398. | c_ast.ID()
  399. | c_ast.Typedef()
  400. | c_ast.ExprList()
  401. | c_ast.CompoundLiteral()
  402. | c_ast.GenericSelection()
  403. | c_ast.StaticAssert()
  404. ):
  405. # These visitors leave the semicolon to the enclosing context,
  406. # so they can also be used in expressions or for clauses.
  407. return indent + self.visit(n) + ";\n"
  408. case c_ast.Compound():
  409. # No extra indentation required before the opening brace of a
  410. # compound - because it consists of multiple lines it has to
  411. # compute its own indentation.
  412. #
  413. return self.visit(n)
  414. case c_ast.If():
  415. return indent + self.visit(n)
  416. case _:
  417. return indent + self.visit(n) + "\n"
  418. def _generate_decl(self, n: c_ast.Decl) -> str:
  419. """Generation from a Decl node."""
  420. s = ""
  421. if n.funcspec:
  422. s = " ".join(n.funcspec) + " "
  423. if n.storage:
  424. s += " ".join(n.storage) + " "
  425. if n.align:
  426. s += " ".join(self.visit(align) for align in n.align) + " "
  427. s += self._generate_type(n.type)
  428. return s
  429. def _generate_type(
  430. self,
  431. n: c_ast.Node,
  432. modifiers: list[c_ast.Node] | None = None,
  433. emit_declname: bool = True,
  434. emit_base_type: bool = True,
  435. ) -> str:
  436. """Recursive generation from a type node. n is the type node.
  437. modifiers collects the PtrDecl, ArrayDecl and FuncDecl modifiers
  438. encountered on the way down to a TypeDecl, to allow proper
  439. generation from it.
  440. emit_base_type controls whether the shared type specifier and its
  441. qualifiers are emitted, independently of the declarator parts.
  442. """
  443. if modifiers is None:
  444. modifiers = []
  445. # ~ print(n, modifiers)
  446. match n:
  447. case c_ast.TypeDecl():
  448. s = ""
  449. if emit_base_type:
  450. if n.quals:
  451. s += " ".join(n.quals) + " "
  452. s += self.visit(n.type)
  453. nstr = n.declname if n.declname and emit_declname else ""
  454. # Resolve modifiers.
  455. # Wrap in parens to distinguish pointer to array and pointer to
  456. # function syntax.
  457. #
  458. for i, modifier in enumerate(modifiers):
  459. match modifier:
  460. case c_ast.ArrayDecl():
  461. if i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl):
  462. nstr = "(" + nstr + ")"
  463. nstr += "["
  464. if modifier.dim_quals:
  465. nstr += " ".join(modifier.dim_quals) + " "
  466. if modifier.dim is not None:
  467. nstr += self.visit(modifier.dim)
  468. nstr += "]"
  469. case c_ast.FuncDecl():
  470. if i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl):
  471. nstr = "(" + nstr + ")"
  472. args = (
  473. self.visit(modifier.args)
  474. if modifier.args is not None
  475. else ""
  476. )
  477. nstr += "(" + args + ")"
  478. case c_ast.PtrDecl():
  479. if modifier.quals:
  480. quals = " ".join(modifier.quals)
  481. suffix = f" {nstr}" if nstr else ""
  482. nstr = f"* {quals}{suffix}"
  483. else:
  484. nstr = "*" + nstr
  485. if not emit_base_type:
  486. return nstr
  487. if nstr:
  488. s += " " + nstr
  489. return s
  490. case c_ast.Decl():
  491. return self._generate_decl(n.type)
  492. case c_ast.Typename():
  493. return self._generate_type(
  494. n.type,
  495. emit_declname=emit_declname,
  496. emit_base_type=emit_base_type,
  497. )
  498. case c_ast.IdentifierType():
  499. return " ".join(n.names) + " "
  500. case c_ast.ArrayDecl() | c_ast.PtrDecl() | c_ast.FuncDecl():
  501. return self._generate_type(
  502. n.type,
  503. modifiers + [n],
  504. emit_declname=emit_declname,
  505. emit_base_type=emit_base_type,
  506. )
  507. case _:
  508. return self.visit(n)
  509. def _parenthesize_if(
  510. self, n: c_ast.Node, condition: Callable[[c_ast.Node], bool]
  511. ) -> str:
  512. """Visits 'n' and returns its string representation, parenthesized
  513. if the condition function applied to the node returns True.
  514. """
  515. s = self._visit_expr(n)
  516. if condition(n):
  517. return "(" + s + ")"
  518. else:
  519. return s
  520. def _parenthesize_unless_simple(self, n: c_ast.Node) -> str:
  521. """Common use case for _parenthesize_if"""
  522. return self._parenthesize_if(n, lambda d: not self._is_simple_node(d))
  523. def _is_simple_node(self, n: c_ast.Node) -> bool:
  524. """Returns True for nodes that are "simple" - i.e. nodes that always
  525. have higher precedence than operators.
  526. """
  527. return isinstance(
  528. n,
  529. (
  530. c_ast.Constant,
  531. c_ast.ID,
  532. c_ast.ArrayRef,
  533. c_ast.StructRef,
  534. c_ast.FuncCall,
  535. c_ast.GenericSelection,
  536. ),
  537. )