From fbe4a5eeab2107dfe03fc097bc1f9627b222adbd Mon Sep 17 00:00:00 2001 From: aqua Date: Sun, 22 Oct 2023 18:42:58 +0300 Subject: Initial commit --- codegen/cgen.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 codegen/cgen.py (limited to 'codegen/cgen.py') diff --git a/codegen/cgen.py b/codegen/cgen.py new file mode 100644 index 0000000..0685a6d --- /dev/null +++ b/codegen/cgen.py @@ -0,0 +1,41 @@ +""" C header generation """ +__license__ = 'GPL-3.0-only' + +from .types import Variable, Function, Struct + +def variable_str(var: Variable): + return f'{var.typedef}{"" if var.typedef.endswith("*") else " "}{var.name};' + +def function_str(func: Function): + args = '' if func.args is None else ', '.join( + f'{T+" " if T is not None else ""}{param}' + for param, T in func.args.items()) + return f'{func.result} {func.name}({args});' + +def function_ptr_str(func: Function): + args = '' if func.args is None else ', '.join( + f'{T+" " if T is not None else ""}{param}' + for param, T in func.args.items()) + return f'{func.result} (*{func.name})({args});' + +def struct_str(struct: Struct): + members = '\n'.join([ f' {nested_object_str(it)}' for it in struct.members ]) + return f"""typedef struct {{ +{members} +}} {struct.name};""" + +def nested_object_str(obj): + if isinstance(obj, Variable): + return variable_str(obj) + if isinstance(obj, Function): + return function_ptr_str(obj) + return None + +def as_str(obj): + if isinstance(obj, Variable): + return variable_str(obj) + if isinstance(obj, Function): + return function_str(obj) + if isinstance(obj, Struct): + return struct_str(obj) + return None -- cgit v1.2.1