Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Regenerate function body, and grab AST for specific function #395

Open
riverratz opened this issue Oct 2, 2020 · 0 comments
Open

Regenerate function body, and grab AST for specific function #395

riverratz opened this issue Oct 2, 2020 · 0 comments

Comments

@riverratz
Copy link

When parsing a C file, I'd like to be able to regenerate the function body for a given function, and get the AST for specifically that function. e.g., example0.c

#include something.h 

void my_example() {
  int data = rand();
  printIntLine(data);
}

int main(int argc, char * argv[]) {
  my_example();
}

I've been attempting to modify func_defs.py. Current code as follows. I need assistance with func_ast and func_body

import pandas as pd

sys.path.extend(['.', '..'])

from pycparser import c_parser, c_ast, parse_file

function_list = []

# A simple visitor for FuncDef nodes that prints the names and
# locations of function definitions.
class FuncDefVisitor(c_ast.NodeVisitor):
    def visit_FuncDef(self, node):
        func_name = str(node.decl.name)
        coord = str(node.decl.coord)

        # if the function name contains the word "example" add it to the list
        if re.search("example", func_name):
            func_ast = the ast for this function   # need help here
            func_body = str(the function body) # need help here
            function_list.append([func_name, coord, function_ast, function_body])
        else: 
            pass


def show_func_defs(filename):
    ast = parse_file(filename,
                    use_cpp=True,
                    cpp_path='clang',
                    cpp_args=['-E', '-I/utils/fake_libc_include'])

    v = FuncDefVisitor()
    v.visit(ast)


if __name__ == "__main__":
    if len(sys.argv) > 1:
        filename  = sys.argv[1]
    else:
        dir = '/Users/me/my_c_examples'
        for filename in glob.iglob(dir + "*/*/*.c", recursive=True):
            try:
                show_func_defs(filename)
            except:
                print("Check  out: ", filename)
                pass

    print(function_list)
    df = pd.DataFrame(function_list, columns=['func_name', 'func_coord', 'func_ast', 'func_body'])
    df.to_csv('my_example_functions_ast.csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants