ast_transforms.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. # ------------------------------------------------------------------------------
  2. # pycparser: ast_transforms.py
  3. #
  4. # Some utilities used by the parser to create a friendlier AST.
  5. #
  6. # Eli Bendersky [https://eli.thegreenplace.net/]
  7. # License: BSD
  8. # ------------------------------------------------------------------------------
  9. from copy import deepcopy
  10. from typing import Any, cast
  11. from . import c_ast
  12. def fix_switch_cases(switch_node: c_ast.Switch) -> c_ast.Switch:
  13. """The 'case' statements in a 'switch' come out of parsing with one
  14. child node, so subsequent statements are just tucked to the parent
  15. Compound. Additionally, consecutive (fall-through) case statements
  16. come out messy. This is a peculiarity of the C grammar. The following:
  17. switch (myvar) {
  18. case 10:
  19. k = 10;
  20. p = k + 1;
  21. return 10;
  22. case 20:
  23. case 30:
  24. return 20;
  25. default:
  26. break;
  27. }
  28. Creates this tree (pseudo-dump):
  29. Switch
  30. ID: myvar
  31. Compound:
  32. Case 10:
  33. k = 10
  34. p = k + 1
  35. return 10
  36. Case 20:
  37. Case 30:
  38. return 20
  39. Default:
  40. break
  41. The goal of this transform is to fix this mess, turning it into the
  42. following:
  43. Switch
  44. ID: myvar
  45. Compound:
  46. Case 10:
  47. k = 10
  48. p = k + 1
  49. return 10
  50. Case 20:
  51. Case 30:
  52. return 20
  53. Default:
  54. break
  55. A fixed AST node is returned. The argument may be modified.
  56. """
  57. assert isinstance(switch_node, c_ast.Switch)
  58. if not isinstance(switch_node.stmt, c_ast.Compound):
  59. return switch_node
  60. # The new Compound child for the Switch, which will collect children in the
  61. # correct order
  62. new_compound = c_ast.Compound([], switch_node.stmt.coord)
  63. # The last Case/Default node
  64. last_case: c_ast.Case | c_ast.Default | None = None
  65. # Goes over the children of the Compound below the Switch, adding them
  66. # either directly below new_compound or below the last Case as appropriate
  67. # (for `switch(cond) {}`, block_items would have been None)
  68. for child in switch_node.stmt.block_items or []:
  69. if isinstance(child, (c_ast.Case, c_ast.Default)):
  70. # If it's a Case/Default:
  71. # 1. Add it to the Compound and mark as "last case"
  72. # 2. If its immediate child is also a Case or Default, promote it
  73. # to a sibling.
  74. new_compound.block_items.append(child)
  75. _extract_nested_case(child, new_compound.block_items)
  76. last_case = new_compound.block_items[-1]
  77. else:
  78. # Other statements are added as children to the last case, if it
  79. # exists.
  80. if last_case is None:
  81. new_compound.block_items.append(child)
  82. else:
  83. last_case.stmts.append(child)
  84. switch_node.stmt = new_compound
  85. return switch_node
  86. def _extract_nested_case(
  87. case_node: c_ast.Case | c_ast.Default, stmts_list: list[c_ast.Node]
  88. ) -> None:
  89. """Recursively extract consecutive Case statements that are made nested
  90. by the parser and add them to the stmts_list.
  91. """
  92. if isinstance(case_node.stmts[0], (c_ast.Case, c_ast.Default)):
  93. nested = case_node.stmts.pop()
  94. stmts_list.append(nested)
  95. _extract_nested_case(cast(Any, nested), stmts_list)
  96. def fix_atomic_specifiers(
  97. decl: c_ast.Decl | c_ast.Typedef | c_ast.Typename,
  98. ) -> c_ast.Decl | c_ast.Typedef | c_ast.Typename:
  99. """Atomic specifiers like _Atomic(type) are unusually structured,
  100. conferring a qualifier upon the contained type.
  101. This function fixes a decl with atomic specifiers to have a sane AST
  102. structure, by removing spurious Typename->TypeDecl pairs and attaching
  103. the _Atomic qualifier in the right place.
  104. """
  105. # There can be multiple levels of _Atomic in a decl; fix them until a
  106. # fixed point is reached.
  107. while True:
  108. decl, found = _fix_atomic_specifiers_once(decl)
  109. if not found:
  110. break
  111. # Match the declaration's qualifiers to the innermost TypeDecl, as for
  112. # ordinary declarations. Qualifiers moved onto pointers belong only on
  113. # those PtrDecl nodes. Also restore the name lost with the wrapper TypeDecl.
  114. typ: Any = decl
  115. while not isinstance(typ, c_ast.TypeDecl):
  116. try:
  117. typ = typ.type
  118. except AttributeError:
  119. return decl
  120. decl.quals = typ.quals[:]
  121. if typ.declname is None:
  122. typ.declname = decl.name
  123. return decl
  124. def _fix_atomic_specifiers_once(
  125. decl: c_ast.Decl | c_ast.Typedef | c_ast.Typename,
  126. ) -> tuple[c_ast.Decl | c_ast.Typedef | c_ast.Typename, bool]:
  127. """Performs one 'fix' round of atomic specifiers.
  128. Returns (modified_decl, found) where found is True iff a fix was made.
  129. """
  130. parent: Any = decl
  131. grandparent: Any = None
  132. node: Any = decl.type
  133. while node is not None:
  134. if isinstance(node, c_ast.Typename) and "_Atomic" in node.quals:
  135. break
  136. try:
  137. grandparent = parent
  138. parent = node
  139. node = node.type
  140. except AttributeError:
  141. # If we've reached a node without a `type` field, it means we won't
  142. # find what we're looking for at this point; give up the search
  143. # and return the original decl unmodified.
  144. return decl, False
  145. assert isinstance(parent, c_ast.TypeDecl)
  146. assert grandparent is not None
  147. # Declaration specifiers are shared by comma-separated declarators. Copy
  148. # the contained type before attaching qualifiers, coordinates, and a name.
  149. typ = deepcopy(node.type)
  150. if typ.coord is None:
  151. # Preserve the declarator coord for _Atomic(T) so TypeDecl doesn't lose
  152. # its location when we replace the wrapper Typename.
  153. typ.coord = parent.coord
  154. # Qualifiers outside _Atomic(T) apply to T itself. In particular, const in
  155. # const _Atomic(int *) qualifies the pointer, not the pointed-to int.
  156. typ.quals = parent.quals + typ.quals
  157. if "_Atomic" not in typ.quals:
  158. typ.quals.append("_Atomic")
  159. cast(Any, grandparent).type = typ
  160. return decl, True