Edit C function declaration with pycparser

413 views Asked by At

I need to write a Python program that parses C source code files and adds a hidden parameter at the end of each function declaration.

More precisely, I need to change something like this:

void f(int a, int b, int c) { ... }

into something like this:

void f(int a, int b, int c, int hiddenArg) { ... }

Obviously, I am going to need to edit all the calls to this function from other functions, too.

I need to do this using pycparser, but I can not figure out the proper way to edit an AST once I have read it. Is there a proper way to do this that I am missing (or any way whatsoever)?

1

There are 1 answers

0
Eli Bendersky On

As an example of modifying the AST, here's changing the function declarations to have a new parameter:

class ParamAdder(c_ast.NodeVisitor):
    def visit_FuncDecl(self, node):
        ty = c_ast.TypeDecl(declname='_hidden',
                            quals=[],
                            type=c_ast.IdentifierType(['int']))
        newdecl = c_ast.Decl(
                    name='_hidden',
                    quals=[],
                    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])

This changes all functions. Obviously, you can add a condition in the visitor to change only certain functions that you're interested in.

You'd modify calls to this function in a similar manner using a visit_FuncCall.