summaryrefslogtreecommitdiff
path: root/codegen/cgen.py
diff options
context:
space:
mode:
Diffstat (limited to 'codegen/cgen.py')
-rw-r--r--codegen/cgen.py41
1 files changed, 41 insertions, 0 deletions
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