mirror of
https://github.com/Lore09/Tesi-Magistrale.git
synced 2025-12-19 12:24:31 +00:00
c code generator
This commit is contained in:
47
src/task_splitter/code_generator.py
Normal file
47
src/task_splitter/code_generator.py
Normal file
@@ -0,0 +1,47 @@
|
||||
|
||||
import ast
|
||||
|
||||
def __get_include_from_annotation(libdeps):
|
||||
|
||||
result = ""
|
||||
|
||||
for lib in libdeps:
|
||||
result += f"#include <{lib}>\n"
|
||||
|
||||
return result
|
||||
|
||||
def __get_main_function_from_function(fun):
|
||||
|
||||
main_function = f"""
|
||||
int main() {{
|
||||
|
||||
{fun['name']}({', '.join(['0' for _ in fun['args'].split(',')])});
|
||||
return 0;
|
||||
}}\n
|
||||
"""
|
||||
return main_function
|
||||
|
||||
def get_code_from_function(fun):
|
||||
|
||||
# Get the function content
|
||||
function_content = f"{fun['return_type']} {fun['name']}({fun['args']}) {fun['content']}"
|
||||
|
||||
# Get the main function
|
||||
main_function = __get_main_function_from_function(fun)
|
||||
|
||||
# Get the dependencies from the annotations
|
||||
libdeps = ""
|
||||
for ann in fun['annotations']:
|
||||
if ann['tag'] == "@LibDeps":
|
||||
libdeps= ast.literal_eval(ann['args'])
|
||||
break
|
||||
|
||||
# Get the include statements
|
||||
include_statements = __get_include_from_annotation(libdeps=libdeps)
|
||||
|
||||
return include_statements + '\n' + function_content + '\n' + main_function
|
||||
|
||||
def build_code_from_functions(functions):
|
||||
|
||||
for fun in functions:
|
||||
fun["code"] = get_code_from_function(fun)
|
||||
@@ -69,24 +69,11 @@ def create_independent_files(functions, output_dir):
|
||||
|
||||
for fun in functions:
|
||||
|
||||
function_content = f"{fun['return_type']} {fun['name']}({fun['args']}) {fun['content']}"
|
||||
|
||||
filename = f"{fun['name']}.c"
|
||||
with open(output_dir + filename, "w") as f:
|
||||
|
||||
# Write the original function
|
||||
f.write(function_content)
|
||||
f.write("\n")
|
||||
|
||||
# Add a main function to call the function
|
||||
main_function = f"""
|
||||
int main() {{
|
||||
// Assuming that the function has no return value
|
||||
{fun['name']}({', '.join(['0' for _ in fun['args'].split(',')])});
|
||||
return 0;
|
||||
}}
|
||||
"""
|
||||
f.write(main_function)
|
||||
# Write the code
|
||||
f.write(fun["code"])
|
||||
|
||||
def extract_functions_from_file(input_file):
|
||||
|
||||
|
||||
Reference in New Issue
Block a user