#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import json from ast_parser import AST_Parser def create_paths_list(dirname, filenames): paths = [] for basename in filenames: path = dirname + basename paths.append(path) return paths def read_files(paths): content = [] for path in paths: file_info = read_file(path) content.append(file_info) return content def read_file(path): with open(path) as f: file_content = f.read() item = {"path": path, "sourcecode": file_content} return item def write_json(header, key): header["outpath"] += "." + key + ".json" with open(header.get("outpath"), "w+") as f: json.dump(header[key], f, indent=4) def prepare_header(header, out_dir): basename = os.path.basename(header.get("path")) outpath = out_dir + basename header["outpath"] = outpath return header def create_simple_AST(ast): elems = {"functions": "", "structs": "", "enums": ""} elems["functions"] = extract_functions_from_ast(ast) return elems # extracts top level functions only (is there anything else in C?) def extract_functions_from_ast(ast): functions = [] children = ast["children"] for child in children: if child["kind"] == "CursorKind.FUNCTION_DECL": functions.append(simple_AST_functions(child)) return functions def simple_AST_functions(func_AST): simple_func = {"name": "", "return_type": "", "arguments": []} simple_func["name"] = func_AST["name"] simple_func["return_type"] = func_AST["result_type"] arguments = [] # check if func has args if "children" in func_AST: for arg_AST in func_AST["children"]: arg_simple = None if arg_AST["kind"] == "CursorKind.PARM_DECL": arg_simple = {"name": "", "type": ""} arg_simple["name"] = arg_AST["name"] arg_simple["type"] = arg_AST["type"] if arg_simple: arguments.append(arg_simple) if arguments: simple_func["arguments"] = arguments return simple_func def main(): input() parser = AST_Parser("/opt/local/libexec/llvm-9.0/lib/libclang.dylib") # Input prefix = r"/Users/heck/local-default/" filenames = ["pEpEngine.h", "keymanagement.h"] # Output out_dir = "data/output/" if not os.path.isdir(out_dir): os.makedirs(out_dir) in_dir = prefix + r"include/pEp/" paths = create_paths_list(in_dir, filenames) headers = read_files(paths) for header in headers: header = prepare_header(header, out_dir) print("processing path: " + header.get("path") + "...") header["AST"] = parser.parse(header["path"], header["sourcecode"]) write_json(header, "AST") header["simple_AST"] = create_simple_AST(header["AST"]) write_json(header, "simple_AST") if __name__ == "__main__": main()