File size: 1,583 Bytes
065fee7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
#-----------------------------------------------------------------
# pycparser: func_defs_add_param.py
#
# Example of rewriting AST nodes to add parameters to function
# definitions. Adds an "int _hidden" to every function.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
import sys
sys.path.extend(['.', '..'])
from pycparser import c_parser, c_ast, c_generator
text = r"""
void foo(int a, int b) {
}
void bar() {
}
"""
class ParamAdder(c_ast.NodeVisitor):
def visit_FuncDecl(self, node):
ty = c_ast.TypeDecl(declname='_hidden',
quals=[],
align=[],
type=c_ast.IdentifierType(['int']))
newdecl = c_ast.Decl(
name='_hidden',
quals=[],
align=[],
storage=[],
funcspec=[],
type=ty,
init=None,
bitsize=None,
coord=node.coord)
if node.args:
node.args.params.append(newdecl)
else:
node.args = c_ast.ParamList(params=[newdecl])
if __name__ == '__main__':
parser = c_parser.CParser()
ast = parser.parse(text)
print("AST before change:")
ast.show(offset=2)
v = ParamAdder()
v.visit(ast)
print("\nAST after change:")
ast.show(offset=2)
print("\nCode after change:")
generator = c_generator.CGenerator()
print(generator.visit(ast))
|